Skip to content Skip to sidebar Skip to footer

Django Nested Objects, Different Serializers GET And POST

this is a follow-up to this question I had here. I can now POST a new AP object using user Primary Key and after commenting this line in the AP serializer user = UserIndexSerialize

Solution 1:

If I understood correctly what you want is to get the nested object during get. I had the same problem which I resolved with this in my serializer.

class APIndexSerializer(serializers.ModelSerializer):
    class Meta:
        model = AP
        fields = ['id','user','name']

    def to_representation(self, obj):
        self.fields['user'] = UserIndexSerializer()
        return super(APIndexSerializer, self).to_representation(obj)

You can with this create with id and get with nested information of user.


Solution 2:

I will give you an example to explain how to use different serializers in GET/POST for relational fields.

There is a Ticket model and it has a foreign key refers to User model. In your POST to create a ticket, you wanna user's id to create the object. In your GET to get ticket's details, you wanna show the user's details rather than ids.

Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)

In your serializer file, you then have

class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('first_name', 'last_name')


class TicketPostSerializer(serializer.ModelSerializer):
    class Meta:
        model = Ticket
        fields = '__all__'


class TicketDetailSerializer(serializer.ModelSerializer):
    user = UserDetailSerializer(read_only=True)
    class Meta:
        model = Ticket
        fields = '__all__'

Then, in Ticket's view function, you then have:

class TicketViewSet(viewsets.ModelViewSet):
    serializer_class = TicketPostSerializer
    def get_serializer_class(self):
        if self.action in ['list', 'retrieve']:
            return TicketDetailSerializer

All set, you are free to go.


Post a Comment for "Django Nested Objects, Different Serializers GET And POST"