Aim to Achieve:
I want all objects where name attribute contains any word from the list.
I have:
JavaScript
x
5
1
list = ['word1','word2','word3']
2
ob_list = data.objects.filter( // What to write here ? )
3
// or any other way to get the objects where any word in list is contained, in
4
// the na-me attribute of data.
5
For example:
if name="this is word2":
Then object with such a name should be returned since word2 is in the list.
Please help!
Advertisement
Answer
You could use Q
objects to constuct a query like this:
JavaScript
1
4
1
from django.db.models import Q
2
3
ob_list = data.objects.filter(reduce(lambda x, y: x | y, [Q(name__contains=word) for word in list]))
4
Edit:
JavaScript
1
2
1
reduce(lambda x, y: x | y, [Q(name__contains=word) for word in list]))
2
is a fancy way to write
JavaScript
1
2
1
Q(name__contains=list[0]) | Q(name__contains=list[1]) | | Q(name__contains=list[-1])
2
You could also use an explicit for loop to construct the Q
object.