【问题标题】:Count a Count with Django Aggregation through multiple Many to Many fields通过多个多对多字段使用 Django 聚合计算一个计数
【发布时间】:2019-05-18 09:40:13
【问题描述】:

给定一个具有两个 M2M 字段的 Django 模型:

class Book(models.Model):
    name = models.CharField(max_length=300)
    authors = models.ManyToManyField(Author)
    publishers = models.ManyToManyField(Publisher)

从作者查询集开始:

authors = Author.objects.filter(...)

我如何annotate a count作者与...互动的出版商(非独家)的数量?

我可以得到作者拥有的书籍数量:

authors.objects.annotate(num_books=Count('book'))

但我想要的是统计所有书籍的出版商数量。

例如,如果数据是这样的:

Book | Authors | Publishers
B1     A1        P1, P2
B2     A2, A1    P1
B2     A2        P1, P2, P3
...

由此产生的带注释的计数将是:

Author |  Publishers
A1        3 (B1-P1, B1-P2, B2-P1)
A2        4 (B2-P1, B3-P1, B3-P2, B3-P3)
...

【问题讨论】:

    标签: django django-orm django-aggregation django-annotate


    【解决方案1】:

    请尝试:

    authors.annotate(num_publishers=Count('book__publishers')).values('id', 'num_publishers')
    

    结果将是:

    <Queryser [{'id': 1, 'num_publishers': 10}, {'id': 2, 'num_publishers': 2}, ... ]>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      相关资源
      最近更新 更多