0

Basically I have this url dispatcher that capture a search term with each word separated by + to be search in the query. I have done this this is works but I think this will hit the performance due to repeated search to the database. Is there a better way to do this?

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)
Nameless
  • 479
  • 1
  • 6
  • 16

2 Answers2

2

You could pre-build your filter, like (untested):

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')
schneck
  • 10,556
  • 11
  • 49
  • 74
0

I think Python list to bitwise operations is simpler when you are using python 2.7

PS: reduce() function has been removed in Python 3, so you can't use it and it is no compatibility.reduce() has been move into module functools

Community
  • 1
  • 1
Neo Ko
  • 1,365
  • 15
  • 25