5 hours ago · Tech · hide · 0 comments

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…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.