How do I do an OR filter in a Django query?

Viewed 242485

I want to be able to list the items that either a user has added (they are listed as the creator) or the item has been approved.

So I basically need to select:

item.creator = owner or item.moderated = False

How would I do this in Django? (preferably with a filter or queryset).

8 Answers

There is Q objects that allow to complex lookups. Example:

from django.db.models import Q

Item.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)

Multiple ways to do so.

1. Direct using pipe | operator.

from django.db.models import Q

Items.objects.filter(Q(field1=value) | Q(field2=value))

2. using __or__ method.

Items.objects.filter(Q(field1=value).__or__(field2=value))

3. By changing default operation. (Be careful to reset default behavior)

Q.default = Q.OR # Not recommended (Q.AND is default behaviour)
Items.objects.filter(Q(field1=value, field2=value))
Q.default = Q.AND # Reset after use.

4. By using Q class argument _connector.

logic = Q(field1=value, field2=value, field3=value, _connector=Q.OR)
Item.objects.filter(logic)

Snapshot of Q implementation

class Q(tree.Node):
    """
    Encapsulate filters as objects that can then be combined logically (using
    `&` and `|`).
    """
    # Connection types
    AND = 'AND'
    OR = 'OR'
    default = AND
    conditional = True

    def __init__(self, *args, _connector=None, _negated=False, **kwargs):
        super().__init__(children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated)

    def _combine(self, other, conn):
        if not(isinstance(other, Q) or getattr(other, 'conditional', False) is True):
            raise TypeError(other)

        if not self:
            return other.copy() if hasattr(other, 'copy') else copy.copy(other)
        elif isinstance(other, Q) and not other:
            _, args, kwargs = self.deconstruct()
            return type(self)(*args, **kwargs)

        obj = type(self)()
        obj.connector = conn
        obj.add(self, conn)
        obj.add(other, conn)
        return obj

    def __or__(self, other):
        return self._combine(other, self.OR)

    def __and__(self, other):
        return self._combine(other, self.AND)
    .............

Ref. Q implementation

Item.objects.filter(field_name__startswith='yourkeyword')
Related