Django raw() query, calculated field in WHERE clause

前端 未结 2 1482
星月不相逢
星月不相逢 2021-01-15 02:14

I\'m wondering if there are any limitations on syntax of raw() method when using calculated fields. Here is a quick example:

Company.objects.raw(\'\'\'SELECT         


        
相关标签:
2条回答
  • 2021-01-15 02:40

    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''')
    
    0 讨论(0)
  • 2021-01-15 02:48

    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''')
      
    0 讨论(0)
提交回复
热议问题