We run Postgres 9.6.5 and Django 2.0. We have a Model
with fields created_at
and value
. We need to calculate a 90-day moving average for a certain date_range
. This is how we do this:
output = []
for i in range(len(date_range)):
output.append(
Model.objects.filter(
created_at__date__range=(date_range[i]-timezone.timedelta(days=90), date_range[i]),
).aggregate(Avg('value'))['value__avg'].days
)
This uses Avg
aggregate function, so it's reasonably fast, however we need one query for every date in date_range
. For longer ranges this means a lot of queries.
Postgres can do this in a single query. My question is - can we somehow do this in a single query using Django ORM?
(I know that I can execute raw SQL with Django ORM, but I wanted to avoid this if possible, which is why I'm asking.)