Using Django admin’s search in your own views

In liu of a real fulltext search engine for Django, you may just want to use the same simple search engine that Django’s admin uses. Unfortunately it’s not readily reusable, so you’ll have to pull it out of the ChangeList.getqueryset in django.contrib.admin.views.main.


  def django_admin_keyword_search(model, keywords):
      """Search according to fields defined in Admin’s search_fields"""
      if not keywords: return []
      fields = model._meta.admin.search_fields

      qs = QuerySet(model)
      for keyword in keywords:
          or_queries = [ Q(**{‘%s__icontains’ % field: keyword}) for field in fields ]
          other_qs = QuerySet(model)
          if qs._select_related:
              other_qs = other_qs.select_related()
          other_qs = other_qs.filter(reduce(operator.or_, or_queries))
          qs = qs & other_qs

      return qs
 
Share it on...
del.icio.us  Digg it  Netscape  Newsvine  reddit  StumbleUpon  Yahoo MyWeb  

One Response to “Using Django admin’s search in your own views”

  1. Petro Says:

    Hmm. That is an interesting option. Thanks.

Leave a Reply


tracker