Installing Postgres Extensions with Django Migrations.

stevenwithph

Stephen Appiah

Posted on April 25, 2023

Installing Postgres Extensions with Django Migrations.

Photo by [Tai Bui](https://unsplash.com/@agforlclassic?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)

It’s absolutely 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(),
    ]
Enter fullscreen mode Exit fullscreen mode

Replace TrigramExtension in lines 1 and 9 with any of the available Postgres operations subclasses. As at 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'),
    ]
Enter fullscreen mode Exit fullscreen mode

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

  1. Run migration, python manage.py migrate

Happy coding!

💖 💪 🙅 🚩
stevenwithph
Stephen Appiah

Posted on April 25, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related