Home > Net >  How to do nested Group By with django orm?
How to do nested Group By with django orm?

Time:10-05

I have the following data:

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?

Here is what I want to do: I want to count the number of books published by each author in a single object. I want to get the following result:

{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}} 

My solution goes something along the lines of:

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

But it is not producing the desired result.

CodePudding user response:

You can post-process the results of the query with the groupby(…) function [Python-doc] of the itertools package [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'))
]
  • Related