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


Question

Aim to Achieve:

I want all objects where name attribute contains any word from the list.

I have:

list = ['word1','word2','word3']
ob_list = data.objects.filter( // What to write here ?  )
// or any other way to get the objects where any word in list is contained, in 
// the na-me attribute of data.

For example:

if name="this is word2": Then object with such a name should be returned since word2 is in the list.

Please help!

1
34
12/27/2012 4:15:19 PM

Accepted Answer

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

from django.db.models import Q

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

50
8/17/2011 5:20:34 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon