Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm implementing a simple LIKE search on my Django website and what I currently use is 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 statement and works quite okay. Now I'd also like to split my search query into terms or words:

words = query.split(' ')

So words now contains a list of words, and I'd like to achieve 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 in case there are more than two words I'd like the statement to grow listing all entries by every word.

Any ideas? Thanks!

like image 768
kovshenin Avatar asked Nov 10 '10 17:11

kovshenin


People also ask

How does filter work in Django?

Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this.

What does filter return in Django?

Django provides a filter() method which returns a subset of data. It accepts field names as keyword arguments and returns a QuerySet object. As database has only one record where name is 'tom' , the QuerySet object contains only a single record.

What is __ GT in Django?

Field Lookups - gt (greater than, or equal to) The gte lookup is used to get records that are larger than, or equal to, a specified value. For a greater than, but not or equal to, search, use the gt lookup.


1 Answers

reduce(operator.or_, sequence_of_Q_objects)
like image 119
Ignacio Vazquez-Abrams Avatar answered Sep 29 '22 15:09

Ignacio Vazquez-Abrams