Menu Close

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

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.

Posted in Python, Python Answers