如何在Django rest式响应中为双方显示非对称的多对多自关系?



目前我的模型中有2个相关类:models.py中的UserProfile类和FriendInvite

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    username = models.TextField()
    friends = models.ManyToManyField('self',through='FriendInvite',
     symmetrical=False)
class FriendInvite(models.Model):
    sender = models.ForeignKey(UserProfile,related_name='fi_sender')
    invitee = models.ForeignKey(UserProfile,related_name='fi_invitee')
    status = models.IntegerField(default=0)
    def __str__(self):
        return '%s invites %s' % (self.sender.username,self.invitee.username)

In serializers.py:

from rest_framework import serializers
from myapp.models import UserProfile
class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile

views.py:

from rest_framework import generics
from myapp.models import UserProfile
from myapp.serializers import UserProfileSerializer
class UserProfileList(generics.ListAPIView):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer

我产生了5个不同的用户和3个不同的朋友关系。但是,当我从服务器收到JSON响应时,它只包括发送邀请的用户,而不包括接收邀请的用户:

[{"id":1,"username":"U1","user":1,"friends":[5]},
{"id":2,"username":"U2","user":2,"friends":[]},
{"id":3,"username":"U3","user":3,"friends":[4]},
{"id":4,"username":"U4","user":4,"friends":[]},
{"id":5,"username":"U5","user":5,"friends":[2]}]

在此例中,U1向U5、U3向U4、U5向U2发出邀请。我如何获得用户发送和接收邀请的结果?

我目前的解决方案是在UserProfile类中定义一个方法,并使用查询来获取我想要的对象集。不过,我还是想知道是否有其他方法可以做到这一点。

...
from itertools import chain
from django.db.models import Q
class UserProfile(models.Model):
    ...
    def get_friends_both(self):
        invitees_list = FriendInvite.objects.filter(Q(sender=self)).values('invitee')
        sender_list = FriendInvite.objects.filter(Q(invitee=self)).values('sender')
        return chain(sender_list,  invitees_list)
class UserProfileSerializer(serializers.ModelSerializer):
    friend_list = serializers.ReadOnlyField(source='get_friends_both')
    class Meta:
        model = UserProfile
        fields = ('friend_list','username','id')
        depth = 1

相关内容

  • 没有找到相关文章

最新更新