Thursday, May 29, 2014

Re: Using IN clause with parameterized raw queries

It works!  Thanks.  It seems so obvious in hindsight that I am kicking myself for not thinking of it.

On Thursday, May 29, 2014 7:26:58 PM UTC-7, Simon Charette wrote:
Did you try:

cursor.execute("SELECT username FROM users WHERE username NOT IN (%s, %s, %s)", ['user_a', 'user_b', 'user_c'])

Le jeudi 29 mai 2014 18:10:04 UTC-4, J Y a écrit :
Let say I have this query I would like to execute:

SELECT username FROM users WHERE username NOT IN ('user_a', 'user_b', 'user_c')

How do you run this using raw()?  I've tried the following:

cursor = connections["db"].cursor()
cursor.execute("SELECT username FROM users WHERE username NOT IN (%s)", ['user_a,user_b,user_c'])

That doesn't work, since the list of user names would not be quoted.  I then tried this:

cursor.execute("SELECT username FROM users WHERE username NOT IN (%s)", ["'user_a','user_b','user_c'"])

Then all the quotes will be escaped, and won't work.

Putting aside the discussion with using the ORM for a moment (there's a good reason for not using it), is it possible to do this using raw queries?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/02e857f7-ad02-4b97-9a62-b1fcd366e49d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment