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?
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
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.
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.
From the Django documentation:
Blog.objects.filter(pk__in=[1, 4, 7])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With