我有以下型号:
class User(models.Model):
name = models.Charfield()
email = models.EmailField()
class Friendship(models.Model):
from_friend = models.ForeignKey(User)
to_friend = models.ForeignKey(User)
这些模型用在以下视图和序列化器中:
class GetAllUsers(generics.ListAPIView):
authentication_classes = (SessionAuthentication, TokenAuthentication)
permission_classes = (permissions.IsAuthenticated,)
serializer_class = GetAllUsersSerializer
model = User
def get_queryset(self):
return User.objects.all()
class GetAllUsersSerializer(serializers.ModelSerializer):
is_friend_already = serializers.SerializerMethodField('get_is_friend_already')
class Meta:
model = User
fields = ('id', 'name', 'email', 'is_friend_already',)
def get_is_friend_already(self, obj):
request = self.context.get('request', None)
if request.user != obj and Friendship.objects.filter(from_friend = user):
return True
else:
return False
因此,基本上,对于GetAllUsers视图返回的每个用户,我想打印出该用户是否是请求者的朋友(实际上,我应该同时检查from_和to_friend,但对于该问题并不重要)
我看到的是,对于数据库中的N个用户,有1个查询可获取所有N个用户,然后在序列化程序的查询中有1xN个查询 get_is_friend_already
有没有办法避免这种情况?也许就像将select_related包含的查询传递给具有相关Friendship行的序列化程序一样?
慕虎7371278
慕哥6287543
守着星空守着你