Parameter escaping for IN queries using Django raw SQL cursor

Searching for this little tidbit didn’t turn anything up and I had to figure it out through trial and error, so I figured I’d share the solution in a publicly searchable location:

If you need to perform an IN lookup in a Django raw SQL cursor.execute() invocation, you can do so by passing the list as a tuple. For instance:

from django.db import connection

# This could be a list, a set, or whatever; probably generated programmatically
list_of_values = [1, 2, 3]
with connection.cursor() as cursor:
    cursor.execute("""
        SELECT *
        FROM my_model_table
        WHERE some_value IN %s
    """, [
        tuple(list_of_values),
    ])
    results = cursor.fetchall()
    # Do something with your results

Not complicated, but also as far as I can tell largely undocumented. Enjoy!

Leave a response