How do I do an OR filter in a Django query?
There is Q
objects that allow to complex lookups. Example:
from django.db.models import QItem.objects.filter(Q(creator=owner) | Q(moderated=False))
You can use the | operator to combine querysets directly without needing Q objects:
result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)
(edit - I was initially unsure if this caused an extra query but @spookylukey pointed out that lazy queryset evaluation takes care of that)
It is worth to note that it's possible to add Q expressions.
For example:
from django.db.models import Qquery = Q(first_name='mark')query.add(Q(email='mark@test.com'), Q.OR)query.add(Q(last_name='doe'), Q.AND)queryset = User.objects.filter(query)
This ends up with a query like :
(first_name = 'mark' or email = 'mark@test.com') and last_name = 'doe'
This way there is no need to deal with or operators, reduce's etc.