4๐
You should override to_representation()
method
Try this,
from rest_framework.serializers import Serializer
class PreguntaSerializer(serializers.ModelSerializer):
usuario = UserSerializer(read_only=True)
categoria_pregunta = serializers.PrimaryKeyRelatedField(queryset=Categoria_pregunta.objects.all())
persons = serializers.PrimaryKeyRelatedField(many=True, queryset=Person.objects.all())
class Meta:
model = Pregunta
fields = '__all__'
def to_representation(self, instance):
if self.context['request'].method == 'POST':
user = UserSerializer(instance.usuario).data
categoria_pregunta = Categoria_preguntaSerializer(instance.categoria_pregunta).data
persons = PersonForPreguntaSerializer(instance.persons, many=True).data
data = {"id": instance.id,
"usuario": user,
"categoria_pregunta": categoria_pregunta,
"persons": persons,
"titulo": instance.titulo,
"descripcion": instance.descripcion
}
return data
return Serializer.to_representation(self, instance)
1๐
I would suggest to have two different fields for read and write purpose. You can add a new field in the serializer persons_data
which can be used for getting the list of persons data in serialized format.
Sample code:
class PreguntaSerializer(serializers.ModelSerializer):
usuario = UserSerializer(read_only=True)
categoria_pregunta = serializers.PrimaryKeyRelatedField(queryset=Categoria_pregunta.objects.all())
persons_data = PersonForPreguntaSerializer(source='persons', many=True, read_only=True)
class Meta:
model = Pregunta
exclude = ('status', )
Since you are using exclude
in Meta
class, persons
field will already be included in both read and write which will accept list of primary key ids which you are passing in the request json.
You can also look into .to_representation()
and .to_internal_value()
methods of the serializer.
From documentation
.to_representation()
โ Override this to support serialization, for read operations.
.to_internal_value()
โ Override this to support deserialization, for write operations.
- [Django]-502 Bad Gateway with DigitalOcean (gunicorn/nginx) using Selenium and Django
- [Django]-Django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail"
- [Django]-Django return json and html depending on client python
- [Django]-Edit the opposite side of a many to many relationship with django generic form
- [Django]-How to access file after upload in Django?