Home > Software design >  DRF ManyToMany field seralize
DRF ManyToMany field seralize

Time:10-02

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:

enter image description here

THE QUESTION IS:

How can I serializer the 'friends' field in a way that I can get the id, user.id and user.username.

CodePudding user response:

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)
    ...
  • Related