[Django]-Django Rest Serializer: Use nested serializer on GET but not POST

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)
๐Ÿ‘คJPG

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.

๐Ÿ‘คRitesh Agrawal

Leave a comment