Django annotate 时 group by 有额外的字
2019-04-17 本文已影响0人
Sunnky
描述:
class Encounter(models.Model):
activity_type = models.CharField(max_length=2,
choices=(('ip','ip'), ('op','op'), ('ae', 'ae')))
cost = models.DecimalField(max_digits=8, decimal_places=2)
class Meta:
order_by = "cost"
查询语句如下:
Encounter.objects.values('activity_type').annotate(Sum('cost'))
打印出sql
语句:
SELECT "encounter_encounter"."activity_type",
SUM("encounter_encounter"."total_cost") AS "total_cost__sum"
FROM "encounter_encounter"
GROUP BY "encounter_encounter"."activity_type",
"encounter_encounter"."total_cost" <<<< THIS MESSES THINGS
ORDER BY "encounter_encounter"."total_cost" DESC
原因:
虽然在查询中没有明确说明,但是模型的Meta
类中的默认排序被添加到查询中,然后将其添加到group by
子句中,因为SQL
需要这样。
解决方案是删除默认排序或添加空order_by()
重置顺序:
>>> Encounter.objects.values('activity_type').annotate(Sum('cost')).order_by()