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

1

6

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!

Abney answered 10/11, 2010 at 17:46 Comment(3)
Don't forget to sanitize your queries or you will be in the same situation that Boby Table's school was.Prophase
what about using fulltext search with djapian?Sherburne
@the_drow: Django (or more correctly, DB-API) deals with that already.Dewan
D
11
reduce(operator.or_, sequence_of_Q_objects)
Dewan answered 10/11, 2010 at 17:50 Comment(2)
Ah, sorry for comment, typo there. Removed. This seems to work, thanks so much, didn't know if this reduce() function and operator.or_Abney
reduce(lambda: q, w: q | Q(...=w), query.split(' '), Q()), maybe too complex for one liner though.Sherburne

© 2022 - 2024 — McMap. All rights reserved.