Installing Postgres Extensions with Django Migrations.

It’s possible to create Postgres extensions without having to log into your database and run it manually. The same task can even be more daunting if you have to do it the Docker way. Django makes it way easier with database migration operations. This way, you and your team members wouldn’t have to worry about extra DevOps work.

In this example, we will learn how to create a pg_trgm (or any other Postgres extension) by just creating a migration file.

  1. Add django.contrib.postgres in INSTALLED_APPS in your project settings.

  2. Create a new migration file in your app’s migration folder. It’s conventional to follow the index of your last migration file. Say, your last migration file is 0012_last_migration_file.py, the new migration file could then be named, 0013_name_of_extension.py.

  3. For installing, pg_trgm, add the following code to the migration file you just created:

from django.contrib.postgres.operations import TrigramExtension
from django.db import migrations

class Migration(migrations.Migration):
    dependencies = [
        ('app_name', '0012_last_migration_file'),
    ]

    operations = [
        TrigramExtension(),
    ]

Replace TrigramExtension in lines 1 and 9 with any of the available Postgres operations subclasses. As of the time of writing these common extension subclasses are available:

BloomExtension, BtreeGinExtension, BtreeGistExtension, CITextExtension, CryptoExtension, HStoreExtension, TrigramExtension, UnaccentExtension

For extensions that are not listed above, use the CreateExtension subclass:

from django.contrib.postgres.operations import CreateExtension
from django.db import migrations


class Migration(migrations.Migration):
    dependencies = [
        ('app_name', 'last_migration_file'),
    ]

    operations = [
        CreateExtension('postgis'),
    ]

replace postgis in line 11 with the name of the extension to be installed.

  1. Run migration, python manage.py migrate

Happy coding!