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.
classAPIndexSerializer(serializers.ModelSerializer):classMeta:
model = AP
fields = ['id','user','name']
defto_representation(self, obj):
self.fields['user'] = UserIndexSerializer()
returnsuper(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
classUserDetailSerializer(serializers.ModelSerializer):
classMeta:
model = Userfields= ('first_name', 'last_name')
classTicketPostSerializer(serializer.ModelSerializer):
classMeta:
model = Ticketfields='__all__'classTicketDetailSerializer(serializer.ModelSerializer):
user = UserDetailSerializer(read_only=True)
classMeta:
model = Ticketfields='__all__'
Then, in Ticket's view function, you then have:
classTicketViewSet(viewsets.ModelViewSet):
serializer_class = TicketPostSerializer
defget_serializer_class(self):
ifself.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"