gpt4 book ai didi

多个注释中的 Django Count()

转载 作者:行者123 更新时间:2023-11-28 19:35:06 25 4
gpt4 key购买 nike

假设我有一个简单的论坛模型:

class User(models.Model):
username = models.CharField(max_length=25)
...

class Topic(models.Model):
user = models.ForeignKey(User)
...

class Post(models.Model):
user = models.ForeignKey(User)
...

现在假设我想查看用户子集中的每个用户有多少主题和帖子(例如,他们的用户名以“ab”开头)。

因此,如果我对每个帖子和主题执行一个查询:

User.objects.filter(username_startswith="ab")
.annotate(posts=Count('post'))
.values_list("username","posts")

产量:

[('abe', 5),('abby', 12),...]

User.objects.filter(username_startswith="ab")
.annotate(topics=Count('topic'))
.values_list("username","topics")

产量:

[('abe', 2),('abby', 6),...]

但是,当我尝试注释两者以获得一个列表时,我得到了一些奇怪的东西:

User.objects.filter(username_startswith="ab")
.annotate(posts=Count('post'))
.annotate(topics=Count('topic'))
.values_list("username","posts", "topics")

产量:

[('abe', 10, 10),('abby', 72, 72),...]

为什么主题和帖子成倍增加?我期望这样:

[('abe', 5, 2),('abby', 12, 6),...]

获取正确列表的最佳方法是什么?

最佳答案

我认为Count('topics', distinct=True)应该做正确的事。这将使用 COUNT(DISTINCT topic.id) 而不是 COUNT(topic.id) 来避免重复。

User.objects.filter(
username_startswith="ab").annotate(
posts=Count('post', distinct=True)).annotate(
topics=Count('topic', distinct=True)).values_list(
"username","posts", "topics")

关于多个注释中的 Django Count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6795202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com