多个注释中的 Django Count()

标签 django annotations count django-queryset

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

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/

相关文章:

python - 无法使用有效的用户名和密码登录 django 管理页面

jquery - 使用 Uploadify 在 Django 中上传文件获取 HTTP 响应代码 403

python - type char exceed 10485760 limit 在我将限制更改为小于 MAX 后仍然显示错误

java - 注释 SOURCE 保留政策

javascript - 如何统计具有元素值的对象?

python - 将自定义响应 header 添加到 APIException

java - @GeneratedValue 注解

java - 基于环境的条件注释

bash - 使用命令行工具计算排序序列中的重复项

MySQL 计数该值是否之前没有出现过