Django SQL OR via filter () & Q (): Dynamic?

I am implementing a simple LIKE search on my Django site and I am currently using the following code:

from django.db.models import Q posts = Post.objects.filter(Q(title__icontains=query)|Q(content__icontains=query)) 

Where query is a string. This results in a LIKE SQL expression and works quite fine. Now I would also like to break my search query into terms or words:

 words = query.split(' ') 

So words now contains a list of words, and I would like to get an SQL statement similar to:

 SELECT ... FROM foo WHERE `title` ILIKE '%word1%' OR `title` ILIKE '%word2%' OR `content` ILIKE '%word1%' OR `content` ILIKE '%word2%' 

And if there are more than two words, I would like the expression to increase, listing all the entries for each word.

Any ideas? Thanks!

+6
django django-queryset django-q
source share
1 answer
 reduce(operator.or_, sequence_of_Q_objects) 
+11
source share

All Articles