Django raw()查询,WHERE子句中的计算字段

时间:2011-03-16 23:40:25

标签: mysql django mysql-error-1054

我想知道在使用计算字段时是否对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语句中使用它。请分享您的经验。谢谢。

2 个答案:

答案 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''')