Categories
Python Answers

How to dynamically compose an OR query filter in Python Django?

Spread the love

To dynamically compose an OR query filter in Python Django, we can call filter with Q objects combined with |.

For instance, we write

values = [1,2,3]

queries = [Q(pk=value) for value in values]
query = queries.pop()
for item in queries:
    query |= item

Article.objects.filter(query)

to create the queries list with a list of Q object with the conditions we want to filter by.

Then we loop through the queries to combine them with |= into query.

Finally, we call filter with query to filter by all the conditions.

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 *