How to Query model where name contains any word in python list? How to Query model where name contains any word in python list? django django

How to Query model where name contains any word in python list?


You could use Q objects to constuct a query like this:

from django.db.models import Qob_list = data.objects.filter(reduce(lambda x, y: x | y, [Q(name__contains=word) for word in list]))

Edit:

reduce(lambda x, y: x | y, [Q(name__contains=word) for word in list]))

is a fancy way to write

Q(name__contains=list[0]) | Q(name__contains=list[1]) | ... | Q(name__contains=list[-1])

You could also use an explicit for loop to construct the Q object.


ob_list = data.objects.filter(name__in=my_list)

And BTW, avoid using the variable name "list" (Or any other python standard keyword), lest you get into some weird bugs later.

Update: (I guess your question was updated too, because when I wrote the answer, I didn't see the part where you wrote you need a contains match and not an exact match)

You can do that using the regex search too, avoiding many Q expressions (which end up using that many where "and" clauses in the SQL, possibly dampening the performance), as follows:

data.objects.filter(name__regex=r'(word1|word2|word3)')


obj_list = [obj for obj in data.objects.all() if any(name in obj.name for name in list)]

Edit: Just re-read your question. Don't know if you can do that with filter but you can do it with a list comprehension or generator expression.