Django为GROUP BY子句添加了一个额外的字段

时间:2018-05-19 16:32:49

标签: django django-models django-orm

这是一个查询:

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"

1 个答案:

答案 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()