【问题标题】:Django raw sql statement with params and likes search带有参数和喜欢搜索的 Django 原始 sql 语句
【发布时间】: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


【解决方案1】:

你可以尝试使用 f-string,像这样


from django.db import connection
start = '2017-12-08T01:56:56.701Z'
end = '2020-12-08T01:56:56.701Z'
def query_example(start, end):
   cursor = connection.cursor()
   
   cursor.execute(
     f'''
     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 {start} and {end}
     '''
   )

   return cursor.fetchall()

然后你可以访问视图中的数据,调用query_example func

def request_data(request):

  data = query_example(...)
  # do something...
  ...
  
  return JsonResponse(data, safe=False)
      or 
  return render(request, "your_template.html", {"data": data})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2015-09-19
    • 2017-02-25
    相关资源
    最近更新 更多