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

廉价感情. 提交于 2019-11-29 14:39:57

问题


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!


回答1:


reduce(operator.or_, sequence_of_Q_objects)


来源:https://stackoverflow.com/questions/4147383/django-sql-or-via-filter-q-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!