我正在制作一个带有评论的django应用程序,并对这些评论进行投票,采用stackoverflow或reddit风格。当选择评论时,我想知道总投票数,以及用户是否对此特定评论进行了投票。我可以像这样使用annotate进行汇总计数:
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)发布于 2012-01-23 17:01:45
根据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))并手动组合这两个列表。
发布于 2012-01-23 13:45:19
我认为这应该会给你你所需要的:
CommentVote.objects.values('comment').filter(comment__video_id=video_id,user=user).annotate(vote_sum=Sum('value')).values_list('comment','vote_sum',)https://stackoverflow.com/questions/8967030
复制相似问题