Django admin search with few words

I'm having problems using search_fields when a search expression has multiple words and I want to search using startswit

I have a class

 class Foo(models.Model): kw = models.CharField(max_length = 255) ... class FooAdmin(admin.ModelAdmin): search_fields = ('^kw',) 

'^' indicates that I want to do a job search. If I search for kw 'foo fuu', django will execute the request:

 select * from app_foo where `foo`.`kw` like 'foo%' and `foo`.`kw` like 'fuu%' 

This query obviously yields null results. What should I do to get the engine to search for 'foo fuu%' ?

+7
source share
3 answers

How about overriding self.query so that split() doesn't work?

 from django.contrib.admin.views.main import ChangeList class UnsplitableUnicode(str): "An object that behaves like a unicode string but cannot be split()" def split(self, *args, **kwargs): return [self] class MultiWordSearchChangeList(ChangeList): "Changelist that allows searches to contain spaces" def get_query_set(self, request): self.query = UnsplitableUnicode(self.query) return super(MultiWordSearchChangeList, self).get_query_set(request) class FooAdmin(admin.ModelAdmin): def get_changelist(self, request, **kwargs): return MultiWordSearchChangeList 
+12
source

As Tai-Tran has already been mentioned, this is a bit messy. Here is the section you will need to edit.

 from django.contrib import admin from django.contrib.admin.views.main import ChangeList class CustomChangeList(ChangeList): def get_query_set(self, request): #Basically copy and paste in entire function and edit the piece copied in here. if self.search_fields and self.query: orm_lookups = [construct_search(str(search_field)) for search_field in self.search_fields] for bit in self.query.split(): or_queries = [models.Q(**{orm_lookup: bit}) for orm_lookup in orm_lookups] qs = qs.filter(reduce(operator.or_, or_queries)) if not use_distinct: for search_spec in orm_lookups: if lookup_needs_distinct(self.lookup_opts, search_spec): use_distinct = True break class FooAdmin(admin.ModelAdmin): def get_changelist(self, request, **kwargs): return CustomChangeList 

From experience, redefining ChangeList caused problems in the future.

+2
source

Here is a link to a snippet that an advanced search can do for the administrator:

http://djangosnippets.org/snippets/2322/

+1
source

All Articles