Django raw() query, calculated field in WHERE clause

本小妞迷上赌 提交于 2019-12-01 14:12:47

It actually has nothing to do with Django itself, but with the way MySQL works.

You can't use aliases in WHERE conditions, because WHERE clause evaluation precedes the aliases evaluation.

You can either:

  • Repeat the clause:

    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''')
    
  • Do a subselect:

    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''')
    
Ian Turton

You can use the HAVING clause for derived columns. BTW - this includes columns which are aggregations e.g. the result of SUM, COUNT etc.

So, the following should work:

Company.objects.raw('''SELECT *,core_location.a + core_location.b as dist
FROM core_location,core_company
HAVING dist<10  
ORDER BY dist''')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!