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

DjangoDjango Queryset

Django Problem Overview


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

Django Solutions


Solution 1 - Django

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

Solution 2 - Django

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)

Solution 3 - Django

It is worth to note that it's possible to add Q expressions.

For example:

from django.db.models import Q

query = Q(first_name='mark')
query.add(Q(email='[email protected]'), 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 = '[email protected]') and last_name = 'doe'

This way there is no need to deal with or operators, reduce's etc.

Solution 4 - Django

You want to make filter dynamic then you have to use Lambda like

from django.db.models import Q

brands = ['ABC','DEF' , 'GHI']

queryset = Product.objects.filter(reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]))

reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]) is equivalent to

Q(brand=brands[0]) | Q(brand=brands[1]) | Q(brand=brands[2]) | .....

Solution 5 - Django

Similar to older answers, but a bit simpler, without the lambda...

To filter these two conditions using OR:

Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))

To get the same result programmatically:

filter_kwargs = {
    'field_a': 123,
    'field_b__in': (3, 4, 5, ),
}
list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))

operator is in standard library: import operator
From docstring: > or_(a, b) -- Same as a | b.

For Python3, reduce is not a builtin any more but is still in the standard library: from functools import reduce


P.S.

Don't forget to make sure list_of_Q is not empty - reduce() will choke on empty list, it needs at least one element.

Solution 6 - Django

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

Solution 7 - Django

This might be useful https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships

Basically it sounds like they act as OR

Solution 8 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMezView Question on Stackoverflow
Solution 1 - DjangoAlex KoshelevView Answer on Stackoverflow
Solution 2 - DjangoAndy BakerView Answer on Stackoverflow
Solution 3 - DjangomarxinView Answer on Stackoverflow
Solution 4 - DjangoAbhishek ChauhanView Answer on Stackoverflow
Solution 5 - DjangofrnhrView Answer on Stackoverflow
Solution 6 - DjangoFurkan SiddiquiView Answer on Stackoverflow
Solution 7 - DjangoDorin RusuView Answer on Stackoverflow
Solution 8 - DjangoRaj Kushwaha RView Answer on Stackoverflow