[Answered ]-Best way to query Django ORM to sum items by category per year (for time series)

1👍

You can post-process the result with groupby [python-doc]:

from itertools import groupby
from operator import itemgetter

data = Book.objects.values(
    'category__description'
    year=TruncYear('written_date'),
).annotate(
    total=Count('id')
).order_by('year', 'category__description')

result = {
    yrs: {r['category__description']: r['total'] for r in rs}
    for yrs, rs in groupby(data, itemgetter('year'))
}

Leave a comment