0

在 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 语句。有任何想法吗?谢谢!

4

1 回答 1

0

您可以尝试使用 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})
于 2020-12-09T01:03:15.997 回答