Categories
Python Answers

How to run Django filter queryset __in for every item in list with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *