Skip to content

Instantly share code, notes, and snippets.

@petersanchez
Created September 19, 2017 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petersanchez/0a5370dcd2d226f3c8c940b9b80e7a47 to your computer and use it in GitHub Desktop.
Save petersanchez/0a5370dcd2d226f3c8c940b9b80e7a47 to your computer and use it in GitHub Desktop.
from django.db.models import Q, Case, When, Value, IntegerField
class SearchResultsAdminMixin(object):
def get_search_results(self, request, queryset, search_term):
''' Show exact match for title and slug at top of admin search results.
'''
qs, use_distinct = \
super(SearchResultsAdminMixin, self).get_search_results(
request, queryset, search_term)
search_term = search_term.strip()
if not search_term:
return qs, use_distinct
def cond_int(query):
return Case(
When(query, then=Value(1)),
default=Value(0),
output_field=IntegerField()
)
qs = qs.annotate(
exact_title=cond_int(Q(title__iexact=search_term)),
exact_slug=cond_int(Q(slug__iexact=search_term)),
)
order_by = []
if qs.filter(exact_title=1).exists():
order_by.append('-exact_title')
if qs.filter(exact_slug=1).exists():
order_by.append('-exact_slug')
if order_by:
qs = qs.order_by(*order_by)
return qs, use_distinct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment