jfried jfried - 4 years ago 193
Python Question

Django QuerySet OR statement

Is there a way to obtain a QuerySet in Django so that the remaining objects satisfy at least one of a number of constrains (i.e. an OR statement)?

Something like:

remaining = Fruits.objects.all()

fruit_type = ['apple', 'orange'] # input from user
for fruit in fruit_type:
remaining = remaining.filter(FruitType__icontains=fruit)


However, the above only returns FruitTypes that contain both 'orange' AND 'apple' (rather than orange OR apple).

Answer Source

You could use Q object to perform complex queryset

from django.db.models import Q

for fruit in fruit_type:
    query |= Q(FruitType__icontains=fruit)

# Query the model
remaining = remaining.filter(query)

Refer to django docs https://docs.djangoproject.com/en/1.10/topics/db/queries/#complex-lookups-with-q for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download