Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 375
Yugal Jindle Avatar asked Aug 17 '11 05:08

Yugal Jindle


1 Answers

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.

like image 125
Ismail Badawi Avatar answered Sep 21 '22 20:09

Ismail Badawi