126 words
1 minute
PostgreSQL full-text search in the Django Admin

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:

def get_search_results(self, request, queryset, search_term):
if not search_term:
return super().get_search_results(
request, queryset, search_term
)
query = SearchQuery(search_term, search_type="websearch")
rank = SearchRank(F("search_document"), query)
queryset = (
queryset
.annotate(rank=rank)
.filter(search_document=query)
.order_by("-rank")
)
return queryset, False

Here’s the full implementation for my personal blog.

PostgreSQL full-text search in the Django Admin
https://mranv.pages.dev/posts/postgresql-full-text-search-in-the-django-admin/
Author
Anubhav Gain
Published at
2024-01-31
License
CC BY-NC-SA 4.0