views:

28

answers:

1

I have a seach by name function, which should return the name of one person, if the search matches the first name or the last name. The problem is that if i search for strings like 'firstname lastname' it doesn't find the name that matches (guess it's because of the space between the words) . What should i do for the search to work? Also, if i want to search with the same search the username (wich is in another table) how can i do it? Thanks a lot!

my code:

 def search(request):
    query = request.GET.get('q', '')
    if query:
        qset1 = (
            Q(first_name__icontains=query) |
            Q(last_name__icontains=query) 
                 )
        results = UserProfile.objects.filter(qset1).distinct()
    else:
        results = []

    return render_to_response("search/searchName.html", {

    'results': results,     
    'query': query},
    context_instance=RequestContext(request))
+3  A: 

Right now your parsing doesn't split the query up at all, you could do that, loop through the results, and build yourself a Q object to place into your query.

import operator
queries = request.GET.get('q').split()
qset1 =  reduce(operator.__or__, [Q(first_name__icontains=query) | Q(last_name__icontains=query) for query in queries])

results = UserProfile.objects.filter(qset1).distinct()

What this basically will do is split the query up, and loop through each word while doing exactly what you're already doing. So if they search for "Frank Podolski" it will check that "Frank" is in the firstname, lastname, and then if "Podolski" is also in the firstname, lastname, rather than the query as a whole.

Of course, there is a lot more you can do to improve search like stemming, removing stop words, etc but that's out of the context of this question.

Bartek
it works, thank you! :)
dana