About Bitwise OR

In Python and Django, if you have a list of elements that you need to combine with bitwise OR i.e. "|" operator, you can use the reduce() function for that. For example:

1
2
3
4
5
6
7
8
9
import operator
from django.db import models

list_of_Q_conditions = [
    models.Q(is_urgent=True),
    models.Q(is_important=True),
    models.Q(is_significant=True),
]
qs = qs.filter(reduce(operator.ior, list_of_Q_conditions))

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 Python 3