如何在 django orm 中使用注释进行嵌套分组?

How to do nested Group By with Annotation in django orm?

我有以下数据:

publisher                    title
--------------------------  -----------------------------------
New Age Books                Life Without Fear
New Age Books                Life Without Fear
New Age Books                Sushi, Anyone?
Binnet & Hardley             Life Without Fear
Binnet & Hardley             The Gourmet Microwave
Binnet & Hardley             Silicon Valley
Algodata Infosystems         But Is It User Friendly?
Algodata Infosystems         But Is It User Friendly?
Algodata Infosystems         But Is It User Friendly?

我想做的是:我想统计每个作者出版了多少本相同书名的书。 我想得到以下结果:

{publisher: New Age Books, title: Life Without Fear, count: 2},
{publisher: New Age Books, title: Sushi Anyone?, count: 1},
{publisher: Binnet & Hardley, title: The Gourmet Microwave, count: 1},
{publisher: Binnet & Hardley, title: Silicon Valley, count: 1},
{publisher: Binnet & Hardley, title: Life Without Fear, count: 1},
{publisher: Algodata Infosystems, title: But Is It User Friendly?, count: 3} 

我的解决方案大致如下:

query_set.values('publisher', 'title').annotate(count=Count('title'))

但它没有产生预期的结果。

Django 有一个特点,即在没有 .order_by() 子句的情况下不会对值执行 GROUP BY。因此,您可以添加一个 .order_by() 子句并使用以下方法处理:

query_set.values('publisher', 'title').annotate(
    count=Count('pk')
).<strong>order_by('publisher', 'title')</strong>

通过将项目“折叠”到一个组中,我们因此计算每个组的主键数。