Issue
I have the following model
class Contact(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='contacts')
friends = models.ManyToManyField('self', blank=True)
def __str__(self):
return self.user.username
When the user log-in, the client make a HTTP request to the following view to get user friends.
class ContactAPIView(generics.RetrieveAPIView):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
lookup_field = 'user__username'
The data returned:
THE QUESTION IS:
How can I serializer the 'friends' field in a way that I can get the id
, user.id
and user.username
.
Solution
You have to use https://www.django-rest-framework.org/api-guide/relations/#nested-relationships
class FriendSerializer(serializers.ModelSerializer):
user_id = ReadOnlyField(source='user.id')
username = ReadOnlyField(source='user.username')
class Meta:
model = Contact
fields = ['id', 'user_id', 'username']
and
class ContactSerializer(serializers.ModelSerializer):
friends = FriendSerializer(many=True, read_only=True)
...
Answered By - qrul
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.