Django 注释和 values() : extra field in 'group by' causes unexpected results

标签 django annotations group-by django-orm

我一定遗漏了一些明显的东西,因为对于这个简单的要求,行为并不像预期的那样。这是我的模型类:

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)

我想找到每种事件类型的总成本。我的查询是:
>>> Encounter.objects.values('activity_type').annotate(Sum('cost'))

其中产生:
>>> [{'cost__sum': Decimal("140.00"), 'activity_type': u'ip'}, 
     {'cost__sum': Decimal("100.00"), 'activity_type': u'op'}, 
     {'cost__sum': Decimal("0.00"), 'activity_type': u'ip'}]

在结果集中有 2 个 'ip' 类型的遭遇。这是因为它不是仅按 activity_type 分组,而是按 activity_type AND 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

我怎样才能让这个查询按预期工作(如果我没有弄错的话,就像 docs 所暗示的那样)并让它只在 activity_type 上做一个组?

最佳答案

正如@Skirmantas 正确指出的那样,问题与 order_by 相关。尽管在查询中没有明确说明,但模型的 Meta 类中的默认排序会添加到查询中,然后将其添加到 group by 子句中,因为 SQL 需要这样做。

解决方案是删除默认排序或添加一个空的 order_by() 以重置排序:

>>> Encounter.objects.values('activity_type').annotate(Sum('cost')).order_by()

关于Django 注释和 values() : extra field in 'group by' causes unexpected results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4968007/

相关文章:

select - 在 Influxdb 中按时间查询获取组中的最后一个时间戳

ruby-on-rails - Rails 按列分组并选择列

python - Django : unique name for object within foreign-key set

django - Django 中使用 Markdown 和 Pygments 进行语法高亮显示

java - 如果没有这个简单项目中启用的注释驱动支持,为什么资源映射不起作用?

java - 如何使用@Configuration配置Spring Webflow 2.3.1?

Django DRF : read_only_fields not working properly

python - 在 python 或 django 中使用 lazyobject

Hibernate:在@Formula 注释中使用 HQL?

python - 如何使用 GROUP BY 和 HAVING 与 SQLAlchemy 和 Postgresql 获取具有最大更新日期时间的行