How to use a list/tuple/array in Django with a raw SQL cursor 0 ▲ Peterbe.com 133 days ago · Tech · hide · Fediverse post This does not work: from django.db import connection 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() It will give you: django.db.utils.ProgrammingError: syntax error at or near "'(1,2,3)'" LINE 4: WHERE id IN '(1,2,3)' It used to work with psycopg v2. Now, in psycopg v3, you have to use the ANY operator. See "You cannot use IN %s with a tuple" This will work: from django.db import connection list_of_values = [1, 2, 3] with connection.cursor() as cursor: cursor.execute( """ SELECT * FROM my_model_table WHERE some_value = ANY(%s) """, [ list_of_values, ], ) results = cursor.fetchall() Note the ANY(%s), and instead of a list that has a tuple, it's a list that has a list. What About a List of Strings Consider... from django.db import connection -list_of_values = [1, 2, 3] +list_of_values = ['foo', 'bar', 'fiz'] with connection.cursor() as… Commenting on Bubbles has been removed. Why? If you want to talk about this post, write to the author, use the comments on their blog if it has them, or reply with a "RE:" post on your own blog. Suggestions? feedback@bubbles.town