如果序列化程序返回空,则Django休息框架

时间:2017-11-09 17:48:28

标签: python django serialization django-rest-framework

我在drf api中实现了一个关注者和关注者系统。

我的关系模型和序列化器:

models.py

class Relationship(models.Model):
    user = models.ForeignKey(User, related_name="primary_user", null=True, blank=True)
    related_user = models.ForeignKey(User, related_name="related_user", null=True, blank=True)
    incoming_status = models.CharField(max_length=40, choices=RELATIONSHIP_CHOICE, default=RELATIONSHIP_CHOICE[0])

    def __str__(self):
        return self.user.username + " " + self.incoming_status + " " + self.related_user.username

serializers.py

class RelationshipSerializer(serializers.ModelSerializer):

    outgoing_status = serializers.SerializerMethodField()

    class Meta:
        model = models.Relationship
        fields = (
            'user',
            'related_user',
            'incoming_status',
            'outgoing_status',
        )

    def get_outgoing_status(self, obj):

        related_user = obj.related_user
        user = obj.user
        try:
            query = models.Relationship.objects.get(user=related_user, related_user=user)
            user_id = query.incoming_status
        except models.Relationship.DoesNotExist:
            user_id = "none"

        return user_id

views.py

class UserViewSet(viewsets.ModelViewSet):
    queryset = models.User.objects.all()
    serializer_class = serializers.UserSerializer

    @detail_route(methods=['get'], url_path='relationship/(?P<related_pk>\d+)')
    def relationship(self, request, pk, related_pk=None):
        user = self.get_object()

        query = models.Relationship.objects.filter(user=user)&\
                models.Relationship.objects.filter(related_user__pk=related_pk)

        serializer = serializers.RelationshipSerializer(query, many=True)

        return Response(serializer.data)

传入状态是您与用户的关系,传出状态是您与用户的关系,例如,这可以返回

[
    {
        "user": 2,
        "related_user": 1,
        "incoming_status": "follows",
        "outgoing_status": "none"
    }
]

这意味着您关注用户,用户不会关注您

当您关注用户时,我的代码工作正常,因为它返回"incoming_status": "follows"然后检查序列化程序中的传出状态。但是当时:

query = models.Relationship.objects.filter(user=user) &
        models.Relationship.objects.filter(related_user__pk=related_pk) 
<{1}}中的

查询返回null,表示传入状态为无序列化器输出views.py,因为查询为空。如果查询为空,如何设置[]

提前致谢

0 个答案:

没有答案