Search code examples
djangodjango-querysetdjango-aggregation

Performing group by and aggregrate Django


I would like to do an average on a subquery with group by, how should I do this in Django without using raw SQL?

See SQL example:

SELECT AVG(calories) AS AVG_DAILY_CALORIES
FROM (
SELECT date, SUM(calories)
FROM products_eaten
GROUP BY date ) daily_calories

I already have the subquery (QuerySet) with values and annotate. Adding aggregate after this fails.

Thanks in advance!


Solution

  • The issue was solved using an aggregrate:

    .aggegrate(avg_daily_calories=Average('calories')/Count('date', distinct=True))