Stephen Appiah
Posted on April 25, 2023
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.
Add
django.contrib.postgres
inINSTALLED_APPS
in 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,0013_name_of_extension.py
.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 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'),
]
replace postgis in line 11 with the name of the extension to be installed.
- Run migration,
python manage.py migrate
Happy coding!
Posted on April 25, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.