django - 获取几个时期的最大值

32s*_*oth 3 python django django-models django-orm django-queryset

我刚开始使用django.我的模型非常简单,包含时间戳和值(温度,每分钟更新).我想检索过去7天中每天的最大值.

我需要查询7次还是有"快捷方式"?

ale*_*cxe 5

你可以利用annotate()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'))
Run Code Online (Sandbox Code Playgroud)