Installing Postgres Extensions with Django Migration Files.

Stephe Codes
2 min readOct 15, 2021

A simple how-to.

Photo by Tai Bui on Unsplash

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:

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:

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

4. Run migration, python manage.py migrate

Happy coding!

--

--