DRF ManyToMany поле seralize
У меня есть следующая модель
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
Когда пользователь входит в систему, клиент делает HTTP-запрос к следующему представлению, чтобы получить друзей пользователя.
class ContactAPIView(generics.RetrieveAPIView):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
lookup_field = 'user__username'
Возвращенные данные:
ВОПРОС ТАКОЙ:
Как я могу сериализовать поле 'friends' таким образом, чтобы получить id
, user.id
и user.username
.
Вы должны использовать 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']
и
class ContactSerializer(serializers.ModelSerializer):
friends = FriendSerializer(many=True, read_only=True)
...