[Django]-Django search for strings containing spaces

13đź‘Ť

âś…

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

Leave a comment