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.
INSTALLED_APPSin your project settings.
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,
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(), ]
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:
For extensions that are not listed above, use the
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'), ]
postgis in line 11 with the name of the extension to be installed.
- Run migration,
python manage.py migrate