【发布时间】:2011-03-17 20:20:49
【问题描述】:
我正在尝试在查询集上实现一些额外的选择,并希望使用 select_related 方法将所需的表添加到查询中的表池中,以便受益于 '__' 语法。
这是一个简单模型的例子:
from django.db import models
# Create your models here.
class testA(models.Model):
code = models.TextField(unique = True)
date = models.DateTimeField(auto_now_add = True)
class testB(models.Model):
text = models.TextField()
a = models.ForeignKey(testA)
这是我要构建的查询:
SELECT (extract(hour from testa.date)) AS hour, testb.text FROM testb INNER JOIN testa ON (testb.a_id = testa.id)
这就是我在 python 中构建它的方式:
testB.objects.all().select_related('a').extra(select = {'hour' : 'extract(hour from testa.date)'}).values('hour','text')
但是当 django 发现我没有使用“testa”表(因为“values”语句)时,他删除了 select_related。所以生成的 SQL 查询失败:
SELECT (extract(hour from testa.date)) AS "hour", "testb"."text" FROM "testb"
如果我删除“值”语句,它可以正常工作:
SELECT (extract(hour from testa.date)) AS "hour", "testb"."id", "testb"."text", "testb"."a_id", "testa"."id", "testa"."code", "testa"."date" FROM "testb" INNER JOIN "testa" ON ("testb"."a_id" = "testa"."id")
但我必须将 values 语句放在我想要聚合的地方,如“计算 a 对象中按日期的小时分组的 b 对象”:
testB.objects.all().select_related('a').extra(select = {'hour' : 'extract(hour from testa.date)'}).values('hour').annotate(count = Count('pk'))
那么实现这一目标的好方法是什么? “计算按另一个对象中的某物分组的对象”?或者有没有办法“强制”django 保留“select_related”表,即使他认为它们没用?
PS:我知道我可以使用额外语句的“tables”参数,但在这种情况下,我必须自己重写连接,我想从 django ORM 中受益
【问题讨论】: