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

PythonDjangoDjango Queryset

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

From the Django documentation:

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

Solution 2 - Python

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.

Solution 3 - Python

From the Django documentation:

Blog.objects.in_bulk([1])
{1: <Blog: Beatles Blog>}

Blog.objects.in_bulk([1, 2])
{1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}

Blog.objects.in_bulk([])
{}

Blog.objects.in_bulk()
{1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>, 3: <Blog: Django Weblog>}

Blog.objects.in_bulk(['beatles_blog'], field_name='slug')
{'beatles_blog': <Blog: Beatles Blog>}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionajwoodView Question on Stackoverflow
Solution 1 - PythoncharlaxView Answer on Stackoverflow
Solution 2 - PythonNileshView Answer on Stackoverflow
Solution 3 - PythonOmoidashitaView Answer on Stackoverflow