Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 710
ajwood Avatar asked Feb 16 '12 02:02

ajwood


People also ask

How do I filter records in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

How filter unique values Django?

If you want to get distinct objects, instead of values, then remove flat=True from the above query, and use values() instead of values_list(). In the above code, we add distinct() at the end of queryset to get distinct values.

What is the difference between filter and get method in Django?

Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters. Show activity on this post. you will get: Pol does not exist. I.e. If you want to run some code depending on whether a single object can be found, use filter.


1 Answers

From the Django documentation:

Blog.objects.filter(pk__in=[1, 4, 7]) 
like image 71
charlax Avatar answered Sep 23 '22 10:09

charlax