我想知道在使用计算字段时是否对raw()方法的语法有任何限制。 这是一个简单的例子:
Company.objects.raw('''SELECT *,core_location.a + core_location.b as dist
FROM core_location,core_company
ORDER BY dist''')
上面的代码按预期工作(结果按计算字段'dist'排序),但是当我添加WHERE子句时,例如:
Company.objects.raw('''SELECT *,core_location.a + core_location.b as dist
FROM core_location,core_company
WHERE dist<10
ORDER BY dist''')
我得到了
(1054,'where子句'中的“未知栏'dist'”)
到目前为止看起来我不能在WHERE子句中使用计算字段,但我可以在ORDER BY语句中使用它。请分享您的经验。谢谢。
答案 0 :(得分:7)
它实际上与Django本身无关,但与MySQL的工作方式无关。
您不能在WHERE条件中使用别名,因为WHERE子句评估先于别名评估。
你可以:
重复以下条款:
Company.objects.raw('''SELECT *,core_location.a + core_location.b as dist
FROM core_location,core_company
WHERE (core_location.a + core_location.b)<10
ORDER BY dist''')
做一个子选择:
Company.objects.raw('''SELECT * FROM (
SELECT *,core_location.a + core_location.b as dist
FROM core_location,core_company
) as subselect
WHERE dist<10
ORDER BY dist''')
答案 1 :(得分:3)
您可以将HAVING
子句用于派生列。 BTW - 这包括聚合的列,例如SUM,COUNT等的结果。
因此,以下内容应该有效:
Company.objects.raw('''SELECT *,core_location.a + core_location.b as dist
FROM core_location,core_company
HAVING dist<10
ORDER BY dist''')