django - get max values over several periods

django, django-models, django-orm, django-queryset, python

Solution

You can make use of `annotate()` and `extra()`:

start_date = date.today() - timedelta(days=7)

MyModel.objects.filter(timestamp__gte=start_date).extra(select={'day': connection.ops.date_trunc_sql('day', 'timestamp')}).values('day').annotate(max_temperature=Max('temperature'))

Problem

I just started with django. My Model is very simple and consists of a timestamp and a value (temperature, updated every minute). I would like to retrieve the max value for each day of the past 7 days. Do I need to query 7 times or is there a 'shortcut'?

Original source