Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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]
total_q = None
return total_q
def get_queryset(self):
query = self.get_query()
if query:
result = self.model.objects.all()
result = self.model.objects.filter(query)
return result
class DemoModelSearch(BaseSearchView):
model = DemoModel
search_fields = ['name','text_body','description',
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