基本上我有这个url调度程序捕获一个搜索项,每个单词用+分隔,以便在查询中搜索。我这样做是有效的,但我认为这会因为重复搜索到数据库而达到性能。有一个更好的方法吗?
def search(request, **kwargs):
context = RequestContext(request)
test = {}
result = BlogPage.objects.select_related('ImageMedia')
if 'search_content' in kwargs:
test['search_content'] = kwargs['search_content']
if kwargs['search_content'] != '0':
search_words = kwargs['search_content'].split('+')
for words in search_words:
result = result.filter(content__icontains=words)
context_dict = {'blog_list': result}
return render_to_response('blog/blog_search.html', context_dict, context)
答案 0 :(得分:2)
您可以预先构建过滤器,例如(未经测试):
from django.db import Q
search_content = kwargs.get('search_content', '')
myfilter = Q()
for term in search_content.split('+'):
myfilter |= Q(content__icontains=term)
result = BlogPage.objects.filter(myfilter).select_related('ImageMedia')
答案 1 :(得分:0)
我认为Python list to bitwise operations在使用python 2.7时更简单
PS: 。reduce()
函数已在Python 3中删除,因此您无法使用它并且它不兼容reduce()
已移入模块functools