Search a column for multiple words using Django queryset
django, django-queryset
Solution
Search engines are better for this task, but you can still do it with basic code. If you're looking for strings containing "A" and "B", you can
Model.objects.filter(string__contains='A').filter(string__contains='B')
or
Model.objects.filter(Q(string__contains='A') & Q(string__contains='B'))
But really, you'd be better going with a simple full text search engine with little configuration, like Haystack/Whoosh
Problem
I have an autocomplete box which needs to return results having input words. However the input words can be partial and located in different order or places. Example: The values in database column (MySQL)- ``` Expected quarterly sales Sales preceding quarter Profit preceding quarter Sales 12 months ``` Now if user types `quarter sales` then it should return both of the first two results. I tried: ``` column__icontains = term #searches only '%quarter sales% and thus gives no results column__search = term #searches any of complete words and also returns last result **{'ratio_name__icontains':each_term for each_term in term.split()} #this searches only sales as it is the last keyword argument ``` Any trick via regex or may be something I am missing inbuilt in Django since this is a common pattern?