[Answered ]-Django Group by multiple times

1👍

You can pass two fields in the .values(…) clause [Django-doc]:

breaks_today.values('teacher', 'break_type').order_by(
    'teacher', 'break_type'
).annotate(count=Count('teacher'))

This will then make dictionaries with three items: the teacher, the break_type and the corresponding count.

You can post-process these to:

from itertools import groupby
from operator import itemgetter

result = {
    k: {
        k2: list(map(itemgetter('count'), v))
        for k2, v in groupby(itemgetter('break_type'), vs)
    }
    for k, vs in groupby(itemgetter('teacher'), breaks_today)
}

Leave a comment