这是一个查询:
speed_by_computer = ChartPoint.objects.filter(
date__gte=start,
date__lt=end,
).values('computer_id') \
.annotate(max_speed=Max('speed'))
以下是此查询生成的SQL查询:
SELECT "computer_id", MAX("speed") AS "max_speed"
FROM "api_chartpoint"
WHERE (
"date" >= 2018-05-17 08:00:00+00:00 AND
"date" < 2018-05-17 09:00:00+00:00
)
GROUP BY "computer_id", "date"
ORDER BY "date" DESC
请注意date
子句中存在意外GROUP BY
。为什么在这里?这是我的预期:
SELECT "computer_id", MAX("speed") AS "max_speed"
FROM "api_chartpoint"
WHERE (
"date" >= 2018-05-17 08:00:00+00:00 AND
"date" < 2018-05-17 09:00:00+00:00
)
GROUP BY "computer_id"
答案 0 :(得分:3)
问题在于默认排序。它在Meta
:
class ChartPoint(models.Model)
...
class Meta:
ordering = ['-date']
删除订单,date
不会添加GROUP BY
:
speed_by_computer = ChartPoint.objects.filter(
date__gte=start,
date__lt=end,
).values('computer_id') \
.annotate(hs_avg=Max('speed'))
.order_by()