Sometimes, we want to run Django filter queryset __in for every item in list with Python.
In this article, we’ll look at how to run Django filter queryset __in for every item in list with Python.
How to run Django filter queryset __in for every item in list with Python?
To run Django filter queryset __in for every item in list with Python, we can use the itertools.reduce
method.
For instance, we write
from operator import and_
from django.db.models import Q
categories = ["holiday", "summer"]
res = Photo.filter(reduce(and_, [Q(tags__name=c) for c in categories]))
to call reduce
with the and_
operator and the list of querysets [Q(tags__name=c) for c in categories]
to combine them with logical AND.
Then we call filter
with the combined query set returned by reduce
.
Conclusion
To run Django filter queryset __in for every item in list with Python, we can use the itertools.reduce
method.