3

I have a query

   select avg(total) from
       (select date, sum(value) as total from table group by some_field, date) as res
   group by week(date)

This is the way I'm getting sum of metrics for each date and show average result grouped by week. How could I get the same result with Django ORM not using raw query.

So far I tried the raw() with this query. Also I can get the results for inner select as

model_obj.objects.filter(some_field='some_value')\
               .values('date', 'some_field')\
               .order_by('date', 'some_field')\
               .annotate(total=Sum('value'))\
               .all()
Dhia
  • 10,119
  • 11
  • 58
  • 69
  • I'm not yet on 1.11, but maybe this will solve your problem: https://docs.djangoproject.com/en/1.11/ref/models/expressions/#subquery-expressions If you manage to solve this problem, don't hesitate to post your own answer for the documentation purposes :) It's a good practice, and will be useful for this quite new Django feature. – Art Apr 20 '17 at 21:59

0 Answers0