【发布时间】:2020-12-08 03:58:34
【问题描述】:
在 Django 中执行原始 sql 时遇到问题。
res = []
start = '2017-12-08T01:56:56.701Z'
end = '2020-12-08T01:56:56.701Z'
with connection.cursor() as cursor:
raw_sql = '''
select
case
when content like '%products%' then 'Products'
else 'Others'
end as name,
count(id) as times
from mytable
where somefield LIKE "%somefieldcontent%"
and created between '%s' and '%s'
'''
cursor.execute(raw_sql, [start, end])
res = cursor.fetchall()
引发此错误:不支持的格式字符''' (0x27)
我尝试直接在 mysql 中执行这个 sql,它可以工作。但它在 Django 环境中不起作用。我认为我对字符串做的一定有问题。
基本上我想使用 params 而不是 concat 来构建 SQL 语句。 有任何想法吗? 谢谢!
【问题讨论】:
-
这是在你的 django 视图中吗?
-
只是某处使用的函数。
标签: python django parameters rawsql