我有以下数据:
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')
).order_by('publisher', 'title')
通过对项目进行排序"到一个组中,因此我们计算每个组的主键的个数。