首页 > 解决方案 > Django:多个annotate()中的Count()

问题描述

我有一个带有ForumPost, ForumComment, ForumPostLike,ForumCommentLike模型的 Django 项目。帖子有多个评论,多个论坛帖子喜欢。评论有多个论坛评论喜欢。每个用户只能赞一次帖子或评论。

我想要什么:我想通过以下方式订购帖子calculated = (num_comments*5 + num_postlikes + num_commentlikes)

问题:使用以下代码,似乎我得到了我想要的。但是有一些奇怪的行为Count()。另外,我想知道是否有更好的方法来实现我的目标。

模型.py

class ForumPost(models.Model):
      # author, title .. etc.

class ForumComment(models.Model):
    post = models.ForeignKey(ForumPost, on_delete=models.CASCADE, related_name='comments')
    #other fields

class ForumPostLike(models.Model):
    liker = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='liked_forumposts')
    post = models.ForeignKey(ForumPost, on_delete=models.CASCADE, related_name='forumpostlikes')

class ForumCommentLike(models.Model):
    liker = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='liked_forumcomments')
    comment = models.ForeignKey(ForumComment, on_delete=models.CASCADE, related_name='forumcommentlikes')

视图.py

posts= ForumPost.objects.filter(published_date__lte=timezone.now()).\
        prefetch_related('comments', 'forumpostlikes')

posts_top = posts\
        .annotate(num_commentlikes=Count('comments__forumcommentlikes__liker'))\
        .annotate(num_postlikes=Count('forumpostlikes', distinct=True))\
            .annotate(num_comments=Count('comments', distinct=True))\
                    .annotate(calculated=(F('num_comments')*Value(5)) + F('num_postlikes') +F('num_commentlikes')*Value(0.5))\
                    .order_by('-calculated')

Count() 的奇怪行为: annotate(num_commentlikes=Count('comments__forumcommentlikes__liker')) 使用此代码,我想从与当前帖子相关的所有评论中获取喜欢的总数。但结果显示2*correct number。一旦我意识到这一点,我将这个数字乘以Value(0.5)反映正确的数字。

如果我使用 distinct 如下: annotate(num_commentlikes=Count('comments__forumcommentlikes__liker', distinct=True)) 此代码仅给我来自第一条评论的点赞数。

为什么会这样?另外,如何改进我的代码?谢谢!

标签: pythondjango

解决方案


推荐阅读