1

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

jfried
  • 98
  • 9

3 Answers3

2

You can do

from django.db.models import Q
query = Q()
for fruit in fruit_type:
    query |= Q(FruitType__icontains=fruit)
remaining = remaining.filter(query)
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
1
fruit_type = ['apple', 'orange']
remaining = Fruits.objects.filter(FruitType__in=fruit_type)
MicroPyramid
  • 1,570
  • 19
  • 22
1

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.

thangtn
  • 856
  • 6
  • 7
  • Is there a way to integrate this within a `for` loop? The user inputs fruit_type so it may be of length 0 up to 10. Worst case scenario I could write 10 `if` statements I suppose. Thanks for the help anyway! – jfried Feb 06 '17 at 06:40
  • yes you could. I edited the anser, hope that helps. – thangtn Feb 06 '17 at 06:43