I wish to customize the way in which search queries across the search_fields.
Is there a way to do it without hacking deeply into the Django code or creating a totally independent view?
For instance, I would like to return the union of the querysets for each of the items of the querystring.split(). So that searching for "apple bar" would return results with EITHER apple OR bar, unlike the default search which applies an AND operator.
you can add an
ModelAdmin
method:you have a request here, so most of the stuff can be view dependent, including url parameters, cookies, sessions etc.
It is very easy to do this in django 1.6
ModelAdmin.get_search_results(request, queryset, search_term) New in Django 1.6.
So I have been using the code from WeizhongTu's answer and found a not-so-obvious error in it. When we try to use both filtering and searching with this code, filtering is shadowed by this line:
queryset = self.model.objects.filter(eval(query_condition))
It is important to use the previous results ONLY. So you must never use
self.model.objects
to obtain the queryset, but only filter the queryset itself. Like this: