Django SQL OR 通过 filter() & Q():动态?
我正在 Django 网站上实现一个简单的 LIKE 搜索,当前使用的是以下代码:
from django.db.models import Q
posts = Post.objects.filter(Q(title__icontains=query)|Q(content__icontains=query))
其中 query
是一个字符串。这会产生一个 LIKE
SQL 语句,并且工作得很好。现在我还想将我的搜索查询拆分为术语或单词:
words = query.split(' ')
因此 words
现在包含一个单词列表,我希望实现类似于以下的 SQL 语句
SELECT ... FROM foo WHERE `title` ILIKE '%word1%' OR `title` ILIKE '%word2%'
OR `content` ILIKE '%word1%' OR `content` ILIKE '%word2%'
:超过两个单词我希望声明能够增长,按每个单词列出所有条目。
有什么想法吗?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)