How can I filter a Django query with a list of values?


Question

I'm sure this is a trivial operation, but I can't figure out how it's done.

There's got to be something smarter than this:

ids = [1, 3, 6, 7, 9]

for id in ids:
    MyModel.objects.filter(pk=id)

I'm looking to get them all in one query with something like:

MyModel.objects.filter(pk=[1, 3, 6, 7, 9])

How can I filter a Django query with a list of values?

1
238
4/22/2019 1:41:55 AM

Accepted Answer

From the Django documentation:

Blog.objects.filter(pk__in=[1, 4, 7])
464
1/17/2017 7:33:41 PM

When you have list of items and you want to check the possible values from the list then you can't use =.

The sql query will be like SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9] which is not true. You have to use in operator for this so you query will be like SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9) for that Django provide __in operator.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon