我有以下数据:
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'))
但是没有产生期望的结果。
您可以使用groupby(…)
对查询结果进行后处理。itertools
的函数[Python-doc]包<一口>[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': {r['title']: r['count']for r in rs }
}
for p, rs ingroupby(qs, itemgetter('publisher'))
]