【发布时间】: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