带注释的Django queryset在序列化过程中被忽略

时间:2018-12-13 16:06:20

标签: django python-3.x django-rest-framework serializer

我有一个ModelViewSet,我想在其中注释list()响应。我已经用注释扩展了查询集,并将字段添加到了序列化器中,但是序列化器只是忽略了新数据,并且根本没有在最终数据中添加该字段。

我也正在使用自定义的get_queryset()(在此显示缩写),它肯定会被调用并产生正确的注释。它只是没有显示在REST API响应中。 如果我在序列化程序字段定义上设置了default=None,它将显示在响应中。

class SequenceSerializer(serializers.ModelSerializer):
    unread=serializers.IntegerField(read_only=True)
    .....

class SequenceViewSet(viewsets.ModelViewSet,ScopedProtectedResourceView):
    authentication_classes = [OAuth2Authentication]
    queryset = Sequence.objects.all()
    serializer_class = SequenceSerializer
    .....

    def get_queryset(self):
        queryset = Sequence.objects.all().filter(<..... some filter>)           
        queryset = queryset.annotate(unread=FilteredRelation('unreadseq',
            condition=Q(unreadseq__userid=self.request.user)))
        print("Seq with unread",queryset.values('id','unread')) ## <<<<this shows the correct data
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data) ##<<< this is missing the annotation

我整天都在朝着这个方向努力,我一生都看不到出了什么问题。 有什么想法吗?

- 更多信息:

class UnreadSeq(models.Model):
    userid = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    seqid = models.ForeignKey(Sequence, on_delete=models.CASCADE)
    class Meta:
        unique_together=('seqid','userid')
        verbose_name = "UnreadSeq"
        verbose_name_plural = "UnreadSeqs"

class Sequence(models.Model):
    userid = models.ForeignKey('auth.User', on_delete=models.SET_NULL,null=True)
    topic = models.ForeignKey('Topic',on_delete=models.CASCADE,null=False,blank=False)
    .....
    class Meta:
        verbose_name = "Sequence"
        verbose_name_plural = "Sequences"

1 个答案:

答案 0 :(得分:1)

我认为该注释不会返回 Integer 。尝试像这样注释(您想要 COUNT unreadseq):

def get_queryset(self):
    mytopics=getMyTopics(self.request,False)
    queryset = Sequence.objects.all().filter(<..... some filter>)

    count_unreadseq = Count('unreadseq', filter=Q(unreadseq__userid=self.request.user))
    queryset=queryset.annotate(unread=count_unreadseq)

    ...
在评论后进行

编辑以获得unreadseq ID

def get_queryset(self):
    mytopics=getMyTopics(self.request,False)
    queryset = Sequence.objects.all().filter(<..... some filter>)

    unreadseq_ids = UnreadSeq.objects.filter(seqid=OuterRef('pk'), userid=self.request.user).values('pk')

    queryset=queryset.annotate(unread=Subquery(unreadseq_ids))
    ...

还需要编辑序列化器:

class SequenceSerializer(serializers.ModelSerializer):
    unread=serializers.IntegerField(read_only=True)
    .....