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)

2 Answers 2

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')
Sign up to request clarification or add additional context in comments.

2 Comments

It gives me this error. unsupported operand type(s) for |=: 'str' and 'Q'
This is because you have to preset myfilter first, e.g. myfilter=Q()
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.