I'm trying to perform a raw SQL query, like so
test = Poll.objects.raw('SELECT * FROM %s', ['polls_poll'])
and it results in an error:
ProgrammingError at ...
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax...
Debug Toolbar shows that Django performs the following SQL query:
SELECT * FROM 'polls_poll'
If I execute this query directly in the MySQL shell, it won't work either, unless I replace single quotes (') with backticks (`).
How do I make Django use backticks? Or what am I doing wrong?
Environment: Django 1.6, MySQL 5.6.14, OS X 10.9.
I think you can only pass query parameters, not field names, so it will not work for table names.
Alternatively, you can try simple string building for your query:
test_query = 'SELECT * FROM %s' % 'polls_poll'
test = Poll.objects.raw(test_query)
Although, string formatting for raw queries is not recommended.
More information: https://docs.djangoproject.com/en/dev/topics/db/sql/#passing-parameters-into-raw
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With