Skip to content

Instantly share code, notes, and snippets.

@smcoll
Created July 25, 2018 21:51
Show Gist options
  • Save smcoll/d9fa4874560b69f5a806aa5c234ea4a2 to your computer and use it in GitHub Desktop.
Save smcoll/d9fa4874560b69f5a806aa5c234ea4a2 to your computer and use it in GitHub Desktop.
Django Postgres database wrapper with `pg_trgm` support.
from django.db.backends.postgresql_psycopg2 import base
class DatabaseWrapper(base.DatabaseWrapper):
""" Postgres database backend with support for operations using trigram indexes, inspired by
https://stackoverflow.com/a/44962928
Put this file in a new module, and point to that module in `settings.DATABASES[<name>]['ENGINE']
"""
def __init__(self, *args, **kwargs):
self.operators.update({
'icontains': 'ILIKE %s',
'istartswith': 'ILIKE %s',
'iendswith': 'ILIKE %s',
})
self.pattern_ops.update({
'icontains': "ILIKE '%%' || {} || '%%'",
'istartswith': "ILIKE {} || '%%'",
'iendswith': "ILIKE '%%' || {}",
})
super(DatabaseWrapper, self).__init__(*args, **kwargs)
def prepare_database(self):
super().prepare_database()
# Check that necessary extensions are installed.
with self.cursor() as cursor:
cursor.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment