【问题标题】:How to do nested Group By with Annotation in django orm?如何在 django orm 中使用 Annotation 进行嵌套 Group By?
【发布时间】: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


【解决方案1】:

Django 有一个特殊性,即不会对没有.order_by() 子句的值执行GROUP BY。因此,您可以添加一个.order_by() 子句并使用:

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

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

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 1970-01-01
    • 2016-04-17
    • 2021-08-01
    • 2019-02-28
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多