Menu Close

How to do an OR filter in a Python Django query?

To do an OR filter in a Python Django query, we can use Q and the | operator.

For instance, we write

from django.db.models import Q

Item.objects.filter(Q(creator=owner) | Q(moderated=False))

to call filter to search for Item items where creator is owner or moderated is False.

We call Q with the conditions we want and combine them with | to do the OR query.

Posted in Python, Python Answers