Python/Django object.filter(pk__in=variable_list)

1.7k Views Asked by At

I'm making a raw query where my result of select id from table looks like this:

[(517L,), (519L,), (526L,), (537L,), (668L,), (670L,), (671L,), (672L,), (673L,)] 

I need to use these ids with the __in filter to receive the correct objects here is my code Note the raw query i've written here is a dummy my real query is complicated and that is why i must use raw query,

from django.db import connection, transaction
cursor = connection.cursor()
cursor.execute("SELECT id FROM table1 WHERE rule=1)
property_list= cursor.fetchall()
object_list = table1.objects.filter(pk__in=property_list)

this results in the following error: argument must be a string or a number, not 'list'

please advise

1

There are 1 best solutions below

0
On BEST ANSWER

The problem is that you have a list of tuples, not a 'raw' list of integers, because fetchall() returns whole rows, not single columns. Try:

pk__in=[p[0] for p in property_list]