在annotate()查询中过滤

时间:2012-01-23 03:56:01

标签: django django-models django-queryset

我正在制作一个django应用程序,其中包含注释并对这些注释进行投票,采用stackoverflow或reddit样式。在选择评论时,我想知道总投票数,以及用户是否对此特定评论进行了投票。我可以使用注释来计算总计数:

video_comments = Comment.objects.filter(video_id=video_id).annotate(vote_sum=Sum('commentvote__value'))

我还可以注释一条评论票的子集吗?类似的东西:

.annotate(user_vote=Sum('commentvote__value').filter(commentvote__user == user))

供参考,这是我的模型:

class Comment(models.Model):
    video_id = models.CharField(max_length=12, db_index=True)
    video_time = models.FloatField()

    comment = models.TextField(max_length=MAX_COMMENT_LENGTH)

    datetime = models.DateTimeField(auto_now_add = True)
    user = models.ForeignKey(User)

class CommentVote(models.Model):
    comment = models.ForeignKey(Comment, db_index=True)
    value = models.IntegerField() # Should be 1 or -1

    datetime = models.DateTimeField(auto_now_add = True)
    user = models.ForeignKey(User, db_index=True)

2 个答案:

答案 0 :(得分:2)

根据this,您可以在注释之前过滤给定字段:

Comment.objects.filter(video_id=video_id).filter(commentvote__user=user))\
               .annotate(user_vote=Sum('commentvote__value'))

不幸的是,这会将评论范围缩小到仅由给定用户投票的那些评论。但你也可以得到其余的评论:

Comment.objects.filter(video_id=video_id).exclude(commentvote__user=user))

并手动合并两个列表。

答案 1 :(得分:0)

我认为这应该能满足你的需求:

CommentVote.objects.values('comment').filter(comment__video_id=video_id,user=user).annotate(vote_sum=Sum('value')).values_list('comment','vote_sum',)
相关问题