0

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.

meesterguyperson
  • 1,726
  • 1
  • 20
  • 31
  • Do you want this to be donespecifically with the django ORM or in SQL ? Or are you fine with python ? – Taek Aug 20 '19 at 16:44
  • @Taek really looking for something in the ORM. I can write the python to do it if I need to, but no sense in that if there's a simple way to get it done via the database. – meesterguyperson Aug 20 '19 at 16:51

0 Answers0