Here's a fun one. Maybe someone can figure this out. Say I have a queryset something like the one below and want to get leads by month per company.
Company.objects.annotate(
month=TruncMonth('leads__date_received')
count=Count('leads')
).values('company__name', 'month', 'count')
This will give me one dict per month for each company, something like this:
{'company_name': 'Amazon', 'month': '2018-01-01', 'count': 333},
{'company_name': 'Amazon', 'month': '2018-02-01', 'count': 444},
{'company_name': 'Amazon', 'month': '2018-03-01', 'count': 555},
This is great but requires further processing if I want to put this in tabular form. What I would like is a result like the following:
{'company_name': 'Amazon', '2018-01-01': 333, '2018-02-01': 444, '2018-03-01': 555}
This is ideal if I already know the month range and can pull out each column value on the basis of the month key. Anyone know a slick way of condensing results like this? Is there some already-built auxiliary function that can do this? Any simple database tricks? Curious to hear.