如何使用 django orm 进行嵌套分组?

How to do nested Group By with 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, titles: {Life Without Fear: 2, Sushi Anyone?: 1}},
{publisher: Binnet & Hardley, titles: {The Gourmet Microwave: 1, Silicon Valley: 1, Life Without Fear: 1}},
{publisher: Algodata Infosystems, titles: {But Is It User Friendly?: 3}} 

我的解决方案大致如下:

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

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

您可以 post-process 使用 groupby(…) function [Python-doc] of the itertools package [Python-doc]:

查询的结果
from django.db.models import Count
from itertools import groupby
from operator import itemgetter

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

result = [
    {
        'publisher': p,
        'titles': {<strong>r['title']: r['count']</strong> for r in rs }
    }
    for p, rs in <strong>groupby(</strong>qs<strong>, itemgetter('publisher'))</strong>
]