Django SQL OR via filter()& Q():动态? [英] Django SQL OR via filter() & Q(): Dynamic?
本文介绍了Django SQL OR via filter()& Q():动态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在Django网站上实现一个简单的LIKE搜索,我目前使用的是以下代码:
from django.db.models import Q
posts = Post.objects.filter(Q(title__icontains = query)| Q(content__icontains = query))
其中查询
是一个字符串。这导致一个 LIKE
SQL语句,并且工作得很好。现在我还想将搜索查询分成字词或单词:
words = query.split('')
所以单词
现在包含一个单词列表,我想要实现一个类似于以下的SQL语句:
SELECT ... FROM foo WHERE`title` ILIKE'% word1%'OR'title'ILIKE'%word2%'
pre>
OR`content` ILIKE'%word1%'OR`content` ILIKE'%word2%'
如果有两个以上的单词,我希望该语句增加每个单词列出所有条目。
任何想法?谢谢!
解决方案
reduce(operator.or_,sequence_of_Q_objects)
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 aLIKE
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!
解决方案reduce(operator.or_, sequence_of_Q_objects)
这篇关于Django SQL OR via filter()& Q():动态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文