I have a problem when performing a raw sql in Django.
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()
It raise this error: unsupported format character ''' (0x27)
I tried to perform this sql directly in mysql, it works. But it does not work in the Django environment. I think must be something wrong I do about the string.
Basically I want to use params instead concat to build the SQL statement. Any ideas? Thanks!
You can try using f-string, something like this
And then you can access the data in views, call query_example func