【问题标题】:How to do nested Group By with django orm?如何使用 django orm 进行嵌套 Group By?
【发布时间】:2021-11-25 02:25:02
【问题描述】:

我有以下数据:

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'))

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

【问题讨论】:

    标签: django database django-models django-rest-framework orm


    【解决方案1】:

    您可以使用itertools package [Python-doc]groupby(…) function [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 in groupby(qs, itemgetter('publisher'))
    ]

    【讨论】:

    • 你我的男人是个传奇。非常感谢!!
    • 嘿伙计。你能进一步指导吗?我的查询集包含重复值,我已使用 distinct() 将其删除。我的查询变成 qs = query_set.values('publisher', 'title').distinct().annotate( count=Count('pk') ).order_by('publisher', 'title') 但它现在正在制造问题.
    • @IbrahimNoor:您能否显示原始print(qs.query) 的结果qs(所以答案中的那个)?
    • 您能否进一步提供一些无法正常工作的示例数据(query_set 模型的表格内容)?
    猜你喜欢
    • 2021-11-24
    • 2016-04-17
    • 1970-01-01
    • 2021-08-01
    • 2019-02-28
    • 1970-01-01
    • 2018-06-13
    • 2018-01-14
    相关资源
    最近更新 更多