Django查询多对多字段计数错误计算

标签 django django-models django-views django-queryset

我正在创建一个 Django 博客网站,但我一度陷入寻找特定帖子的点赞数的困境。我创建了一个显示所有帖子的网页。现在我面临的问题是点赞数计算错误。

发布模型 ->

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    title = models.CharField(max_length=255)   
    description = models.CharField(max_length=1000,null=True)
    Tags = models.CharField(max_length = 255,null=True,blank=True)
    Created_date = models.DateTimeField(auto_now_add=True)
    Updated_date = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    Likes = models.ManyToManyField(to=User, related_name='Post_likes')
    favourites = models.ManyToManyField(to=User,blank=True,related_name="favourite")

    def __str__(self):
        return self.title

在 Views.py 文件中查询以获取所有帖子 ->

posts =  Post.objects.select_related().prefetch_related('images_set').annotate(Count('comments_post')).annotate(Count('Likes')).all()

现在,当我在模板中看到 post.Likes__count 时,它显示一篇特定帖子的错误计数为 6,但当我使用 post.likes.count() 时,它显示数为 3。

对于其他帖子,它们都显示相同的结果。我无法找出为什么会发生这种情况。 这是该特定帖子的结果 ->

{'post_id': 22, 'user_id': 1, 'title': 'wkjdfh', 'description': 'kjwdfn', 'Tags': '.,smdf,m', 'category': <Category: Shoes>, 'userName': 'admin', 'images': <QuerySet [<Images: Images object (10)>, <Images: Images object (11)>, <Images: Images object (12)>, <Images: Images object (13)>]>, 'comments_count': 6, 'likesCount': 6, 'actualLikeCount': 3}

发生这种情况非常奇怪,我知道这是有原因的,但我无法找出原因。

最佳答案

根据 Django 文档:

Combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries

链接:https://docs.djangoproject.com/en/4.0/topics/db/aggregation/#combining-multiple-aggregations

尝试使用.annotate(Count(...),distinct=True)

关于Django查询多对多字段计数错误计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71385707/

相关文章:

python - 在 Django 中,如何将 Request.response 重新打包为 Django 响应?

python - Django在同一数据表的多个字段中搜索查询

python - nginx+uwsgi+django,uwsgi中好像有什么奇怪的缓存,帮帮我

python - django 在生产环境中与主管一起启动 celery 守护进程

django - 如何在 Django 中压缩压缩迁移?

python - 无法在 Django 模型中设置默认值

python - 如何将 Avg() 舍入到最接近的整数? Django

python - 我怎样才能做这样一个典型的单元测试?

mysql - 频繁更新django模型的某一字段

python - Django 无法导入名称 x