Django SQL OR via filter()&Q():动态?

时间:2022-07-19 15:45:27

I'm implementing a simple LIKE search on my Django website and what I currently use is the following code:

我正在我的Django网站上实现一个简单的LIKE搜索,我目前使用的是以下代码:

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:

其中query是一个字符串。这导致LIKE SQL语句并且工作正常。现在,我还想将搜索查询拆分为术语或单词:

words = query.split(' ')

So words now contains a list of words, and I'd like to achieve an SQL statement similar to:

所以单词现在包含一个单词列表,我想实现类似于以下的SQL语句:

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 个解决方案

#1


11  

reduce(operator.or_, sequence_of_Q_objects)

#1


11  

reduce(operator.or_, sequence_of_Q_objects)