Database migration operations

All of these operations are available from the django.contrib.postgres.operations module.

Creating extension using migrations

You can create a PostgreSQL extension in your database using a migration file. This example creates an hstore extension, but the same principles apply for other extensions.

Set up the hstore extension in PostgreSQL before the first CreateModel or AddField operation that involves HStoreField by adding a migration with the HStoreExtension operation. For example:

  1. from django.contrib.postgres.operations import HStoreExtension
  2. class Migration(migrations.Migration):
  3. ...
  4. operations = [
  5. HStoreExtension(),
  6. ...
  7. ]

The operation skips adding the extension if it already exists.

For most extensions, this requires a database user with superuser privileges. If the Django database user doesn’t have the appropriate privileges, you’ll have to create the extension outside of Django migrations with a user that has them. In that case, connect to your Django database and run the query CREATE EXTENSION IF NOT EXISTS hstore;.

Changed in Django 3.2:

In older versions, the pre-existence of the extension isn’t checked.

CreateExtension

class CreateExtension(name)

An Operation subclass which installs a PostgreSQL extension. For common extensions, use one of the more specific subclasses below.

  • name

    This is a required argument. The name of the extension to be installed.

BloomExtension

class BloomExtension

Installs the bloom extension.

BtreeGinExtension

class BtreeGinExtension

Installs the btree_gin extension.

BtreeGistExtension

class BtreeGistExtension

Installs the btree_gist extension.

CITextExtension

class CITextExtension

Installs the citext extension.

CryptoExtension

class CryptoExtension

Installs the pgcrypto extension.

HStoreExtension

class HStoreExtension

Installs the hstore extension and also sets up the connection to interpret hstore data for possible use in subsequent migrations.

TrigramExtension

class TrigramExtension

Installs the pg_trgm extension.

UnaccentExtension

class UnaccentExtension

Installs the unaccent extension.

Managing collations using migrations

New in Django 3.2.

If you need to filter or order a column using a particular collation that your operating system provides but PostgreSQL does not, you can manage collations in your database using a migration file. These collations can then be used with the db_collation parameter on CharField, TextField, and their subclasses.

For example, to create a collation for German phone book ordering:

  1. from django.contrib.postgres.operations import CreateCollation
  2. class Migration(migrations.Migration):
  3. ...
  4. operations = [
  5. CreateCollation(
  6. 'german_phonebook',
  7. provider='icu',
  8. locale='und-u-ks-level2',
  9. ),
  10. ...
  11. ]

class CreateCollation(name, locale, **, provider=’libc’, deterministic=True*)

Creates a collation with the given name, locale and provider.

Set the deterministic parameter to False to create a non-deterministic collation, such as for case-insensitive filtering.

class RemoveCollation(name, locale, **, provider=’libc’, deterministic=True*)

Removes the collations named name.

When reversed this is creating a collation with the provided locale, provider, and deterministic arguments. Therefore, locale is required to make this operation reversible.

Restrictions

Non-deterministic collations are supported only on PostgreSQL 12+.

Concurrent index operations

PostgreSQL supports the CONCURRENTLY option to CREATE INDEX and DROP INDEX statements to add and remove indexes without locking out writes. This option is useful for adding or removing an index in a live production database.

class AddIndexConcurrently(model_name, index)

Like AddIndex, but creates an index with the CONCURRENTLY option. This has a few caveats to be aware of when using this option, see the PostgreSQL documentation of building indexes concurrently.

class RemoveIndexConcurrently(model_name, name)

Like RemoveIndex, but removes the index with the CONCURRENTLY option. This has a few caveats to be aware of when using this option, see the PostgreSQL documentation.

Note

The CONCURRENTLY option is not supported inside a transaction (see non-atomic migration).

Adding constraints without enforcing validation

New in Django 4.0.

PostgreSQL supports the NOT VALID option with the ADD CONSTRAINT statement to add check constraints without enforcing validation on existing rows. This option is useful if you want to skip the potentially lengthy scan of the table to verify that all existing rows satisfy the constraint.

To validate check constraints created with the NOT VALID option at a later point of time, use the ValidateConstraint operation.

See the PostgreSQL documentation for more details.

class AddConstraintNotValid(model_name, constraint)

Like AddConstraint, but avoids validating the constraint on existing rows.

class ValidateConstraint(model_name, name)

Scans through the table and validates the given check constraint on existing rows.

Note

AddConstraintNotValid and ValidateConstraint operations should be performed in two separate migrations. Performing both operations in the same atomic migration has the same effect as AddConstraint, whereas performing them in a single non-atomic migration, may leave your database in an inconsistent state if the ValidateConstraint operation fails.