0

I have a list of strings, which will be generated dynamically. So it will be of variable length:

keywords = ['apples','oranges','bananas']

I have a model Fruitsalad, with a field 'description'. Lets say I want to find all Fruitsalads with either 'apples', 'oranges' or 'bananas' in the 'description' field

results = Fruitsalad.objects.filter(Q(description__icontains=keywords[0]) | Q(description__icontains=keywords[1] | Q(description__icontains=keywords[2])

How could I generate the above query when I don't know in advance how long the 'keywords' list will be?

O James
  • 189
  • 1
  • 12

1 Answers1

0

You should iterate over your array, and do a union on each result

allresults = Fruitsalad.objects.all()
keywords = ['apples','oranges','bananas']
queryset = None
for keyword in keywords:
    if queryset == None:
        queryset = allresults.filter(description__icontains=keyword)
    else:
        queryset = queryset.union(allresults.filter(description__icontains=keyword))

#here are the desired results
print(queryset)
Walucas
  • 2,549
  • 1
  • 21
  • 44