Using IN clause with parameterized raw queries

23 views
Skip to first unread message

J Y

unread,
May 29, 2014, 6:10:04 PM5/29/14
to django...@googlegroups.com
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?

Simon Charette

unread,
May 29, 2014, 10:26:58 PM5/29/14
to django...@googlegroups.com
Did you try:

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

J Y

unread,
May 29, 2014, 11:35:40 PM5/29/14
to django...@googlegroups.com
It works!  Thanks.  It seems so obvious in hindsight that I am kicking myself for not thinking of it.
Reply all
Reply to author
Forward
0 new messages