Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
PostgreSQL full-text search in the Django Admin#
Django 3.1 introduces PostgreSQL search_type="websearch" - which gives you search with advanced operators like "phrase search" -excluding. James Turk wrote about this here, and it’s also in my weeknotes.
I decided to add it to my Django Admin interface. It was really easy using the get_search_results() model admin method, documented here.
My models already have a search_document full-text search column, as described in Implementing faceted search with Django and PostgreSQL. So all I needed to add to my ModelAdmin subclasses was this:
1 def get_search_results(self, request, queryset, search_term):2 if not search_term:3 return super().get_search_results(4 request, queryset, search_term5 )6 query = SearchQuery(search_term, search_type="websearch")7 rank = SearchRank(F("search_document"), query)8 queryset = (9 queryset10 .annotate(rank=rank)11 .filter(search_document=query)12 .order_by("-rank")13 )14 return queryset, FalseHere’s the full implementation for my personal blog.