【发布时间】:2021-11-24 23:18:33
【问题描述】:
我有以下数据:
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'))
但它没有产生预期的结果。
【问题讨论】:
-
query_set.values('publisher', 'title').annotate(count=Count('pk')).order_by('publisher', 'title'). -
嘿!非常感谢。它奏效了。你能解释一下你的答案吗?
-
它实际上更像是 Django 的一个特性,它强制将字段添加到
GROUP BY子句中。我猜添加.group_by子句可能更有意义。
标签: django database django-models django-rest-framework orm