Skip to content

Instantly share code, notes, and snippets.

@muzhig
Created January 7, 2013 09:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muzhig/4473717 to your computer and use it in GitHub Desktop.
Save muzhig/4473717 to your computer and use it in GitHub Desktop.
Django-admin-like configurable search view
from django.db.models import Q
from django.views.generic import ListView
import itertools
class BaseSearchView(ListView):
search_fields = []
def get_search_fields(self):
return self.search_fields
query_key = 'q'
def get_query_key(self):
return self.query_key
def get_query(self):
query = self.request.GET.get(self.get_query_key(),'')
words = [w.strip().lower() for w in query.split(' ') if w]
or_queries = [Q(**{f + "__icontains": w}) \
for w, f in \
itertools.product(words, self.get_search_fields())]
if len(or_queries) > 1:
total_q = reduce(lambda a, b: a | b, or_queries)
elif len(or_queries) == 1:
total_q = or_queries[0]
else:
total_q = None
return total_q
def get_queryset(self):
query = self.get_query()
if query:
result = self.model.objects.all()
else:
result = self.model.objects.filter(query)
return result
class DemoModelSearch(BaseSearchView):
model = DemoModel
search_fields = ['name','text_body','description',
'directory__title',
'owner__name','owner__email','owner__group__name']
def get_query(self):
query = super(DemoModelSearch, self).get_query()
final_query = Q(is_active__exact= True)
if query:
final_query &= query
return final_query
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment