3

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.

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but it does not work. global name 'polls_poll' is not defined
Thanks, I have improved my answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.