美文网首页
Django annotate 时 group by 有额外的字

Django annotate 时 group by 有额外的字

作者: Sunnky | 来源:发表于2019-04-17 16:20 被阅读0次

描述:

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

相关文章

网友评论

      本文标题:Django annotate 时 group by 有额外的字

      本文链接:https://www.haomeiwen.com/subject/gpmnwqtx.html