【问题标题】:Executing raw SQL with python3/Django 1.7使用 python3/Django 1.7 执行原始 SQL
【发布时间】:2015-01-11 13:07:27
【问题描述】:

我正在使用 simple_history,因为我需要模型的历史数据。 我有一个名为 po_staff 的模型,它有一个名为 pool_historicalpo_staff 的“历史”模型。 现在我想获得一个基于 pool_historicalpo_staff 的查询集,其中包含每个员工的最后一条记录(我试图使其尽可能简单,因为真正的查询要复杂得多)。 我目前正在使用 SQLLite

历史模型包含以下数据:

ID staff_nr valid      staff_firstname staff_lastname
1  111      01/01/2014 Firstname1      Lastname1
2  3        01/01/2014 Firstname2      Lastname2
2  3        01/04/2014 Firstname2      Lastname2_new #Employee has changed his Lastname

此代码运行良好(按字母顺序排列):

qs = po_staff.history.raw ('SELECT * FROM pool_historicalpo_staff '
     'WHERE clientID_id is %s and companyID_id is %s '
     'GROUP BY id '
     'ORDER BY staff_name, staff_surname ',
     [client_id, company_id])

我必须使用“id”进行分组,因为可以从用户更改staff_nr(但它仍然是同一个员工)。

问题 1: 用户可以在alpabetical和staff_id之间选择结果的顺序

为了实现这一点,我在查询中添加了第三个参数:

if order == 1:
    order_by = "staff_name, staff_surname"
else:
    order_by = "staff_nr"
qs = po_staff.history.raw ('SELECT * FROM pool_historicalpo_staff '
     'WHERE clientID_id is %s and companyID_id is %s '
     'GROUP BY id '
     'ORDER BY %s ',
     [client_id, company_id, order_by])

查询有效,但不是按字母顺序,而是按“id”排序。

问题 2: 也必须为其他模型执行查询。只是模型和 order_by 会有所不同。 我不想为每个模型编写几乎相同的查询,因此我尝试使其更灵活:

model      = ....  # instance of current model
order_by   = ....  # gets the choosen order for current model, p.e. "staff_name, staff_surname"
model_name = ....  # gets the model name, p.e. "pool_historicalpo_staff"

qs = model.history.raw ('SELECT * FROM %s '
     'WHERE clientID_id is %s and companyID_id is %s '
     'GROUP BY id '
     'ORDER BY %s ',
     [model_name, client_id, company_id, order_by])

执行此查询时出错:

Request Method:     GET
Request URL:    http://127.0.0.1:8000/framework/21/?view=kanban
Django Version:     1.7
Exception Type:     OperationalError
Exception Value:    near "?": syntax error
Exception Location:     c:\python34\lib\site-packages\django\db\backends\sqlite3\base.py in     
                        execute, line 485
Python Executable:  c:\python34\python.EXE
Python Version:     3.4.0

我希望我清楚地解释了一切。 我是 django 新手,这是我的第一个原始 SQL

非常感谢您的帮助!

【问题讨论】:

    标签: python django rawsql


    【解决方案1】:

    这似乎类似于Django: MySQL syntax error when passing parameters to raw SQL query

    简短回答:您只能将参数传递给查询。要支持替换部分 SQL 语法(如表名),您需要分两遍构建查询,在第二遍中仅将实际参数传递给查询。

    希望这会有所帮助。

    【讨论】:

    • 感谢 bimsapi。但是我该怎么做(对不起,我是新人)?你有一个简短的例子吗?非常感谢!!
    • 在提供的链接中也有一个示例。基本上类似于sql = 'select * from {} where foo = %s'.format(table_name),然后是model.history.raw(sql, params)。第一遍使用 Python format 插入表名(使用 {} 占位符 - 请参阅 docs.python.org/2/library/string.html#string-formatting),第二遍实际运行查询(使用 %s 占位符)。
    • 谢谢,我希望避免查询的字符串格式,但如果这是唯一的方法......
    猜你喜欢
    • 2017-04-08
    • 2014-12-18
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2011-04-15
    • 2021-12-05
    相关资源
    最近更新 更多