【问题标题】:Django GROUP BY including unnecessary columns?Django GROUP BY 包括不必要的列?
【发布时间】:2015-03-26 12:10:25
【问题描述】:

我的Django代码如下

qs = Result.objects.only('time') qs = qs.filter(organisation_id=1) qs = qs.annotate(Count('id'))

它被翻译成下面的 SQL:

SELECT "myapp_result"."id", "myapp_result"."time", COUNT("myapp_result"."id") AS "id__count" FROM "myapp_result" WHERE "myapp_result"."organisation_id" = 1 GROUP BY "myapp_result"."id", "myapp_result"."organisation_id", "myapp_result"."subject_id", "myapp_result"."device_id", "myapp_result"."time", "myapp_result"."tester_id", "myapp_result"."data"

如您所见,GROUP BY 子句以我想要的字段 (id) 开头,然后继续列出所有其他字段。有什么办法可以说服 Django 不要像这样指定所有单个字段?

如您所见,即使使用 .only('time') 也不会阻止 Django 列出所有其他字段,但仅在此 GROUP BY 子句中。

我想这样做的原因是避免the issue described here 在涉及 JSON 字段时 PostgreSQL 不支持注释。我不想放弃原生 JSON 支持(所以我实际上并没有使用 django-jsonfield)。如果我在不引用 "myapp_result"."data"(模型上唯一的 JSON 字段)的情况下手动发出查询,该查询就可以正常工作。所以如果我能说服 Django 不要提及它,我会没事的!

【问题讨论】:

    标签: django postgresql orm


    【解决方案1】:

    only 仅延迟加载某些字段,即它允许延迟加载大的或未使用的字段。除非您确切地知道自己在做什么以及为什么需要它,否则通常不应使用它,因为它只不过是一种性能提升器,而不是经常降低不当使用时的性能。

    您要查找的是values()(或values_list()),它实际上排除了某些字段,而不仅仅是延迟加载。这将返回一个字典(或列表)而不是模型实例,但这是告诉 Django 不要考虑其他字段的唯一方法:

    qs = (Result.objects.filter_by(organisation_id=1)
                .values('time').annotate(Count('id')))
    

    【讨论】:

      猜你喜欢
      • 2010-12-06
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多