使用@var:= a.property和django raw sql

时间:2016-02-23 16:41:51

标签: python mysql django cursor

使用cursor.execute(“”),django在我们使用@var的任何地方返回NULL,但是当我们打印出cursor._executed并在我们的mysql客户端中运行它时,它运行正常。

我们的django + mysql示例:

cursor.execute("""
    select 
        @varA := a.property as `my prop`,
        @varA / 100 as `calc prop`
    from
        my_table a;
""")

返回的数据将是:

[
    {
        'my prop' : 1234,
        'calc prop' : null
    }
]

django在这做什么,我错过了一些明显的东西吗? :S

任何指针或想法都会非常感激,欢呼

1 个答案:

答案 0 :(得分:0)

我不得不问,你的用例是什么? Django's ORM可以很容易地用于查询此类表格,如果它是app.Model的一部分。它的表达足以allow manipulation of values,就像你的问题一样:

from django.db.models import F

results = MyTable.objects.annotate(my_prop='property', calc_prop=F('property') / 100)

无论如何,在您希望在ORM之外执行查询的特殊(/罕见)情况下,请使用raw SQL queries

如果仍然不够,对于真正精细的直接访问数据库,您可能依赖cursor.execute(),但正如in the docs所述,正确的方法是获取结果游标执行:

cursor.execute("""
    select 
        @varA := a.property as `my prop`,
        @varA / 100 as `calc prop`
    from
        my_table a;
""")
one_result = cursor.fetchone()
all_results = cursor.fetchall()