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

ajwood picture ajwood · Feb 16, 2012 · Viewed 211.3k times · Source

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?

Answer

charlax picture charlax · Feb 16, 2012

From the Django documentation:

Blog.objects.filter(pk__in=[1, 4, 7])