数据库迁移操作

    你可以使用迁移文件在数据库中创建一个 PostgreSQL 扩展。这个例子创建了一个 hstore 扩展,但同样的原理也适用于其他扩展。

    在涉及到 的第一个 CreateModelAddField 操作之前,通过添加 HStoreExtension 操作的迁移,在 PostgreSQL 中设置 hstore 扩展。例如:

    The operation skips adding the extension if it already exists.

    对于大多数扩展来说,这需要一个具有超级用户权限的数据库用户。如果 Django 数据库的用户没有相应的权限,你就必须在 Django 迁移之外用一个有权限的用户创建扩展。在这种情况下,连接到你的 Django 数据库,并运行查询 CREATE EXTENSION IF NOT EXISTS hstore;

    Changed in Django Development version:

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

    CreateExtension

    class CreateExtension(name)

    一个安装 PostgreSQL 扩展的 Operation 子类。对于普通的扩展,请使用下面一个更具体的子类。

    • name

      这是一个必要的参数。要安装的扩展名。

    BloomExtension

    class BloomExtension

    New in Django 3.1.

    安装 bloom 扩展。

    BtreeGinExtension

    class BtreeGinExtension

    class BtreeGistExtension

    安装 扩展。

    CITextExtension

    class CITextExtension

    安装 citext 扩展。

    CryptoExtension

    class CryptoExtension

    安装 pgcrypto 扩展。

    HStoreExtension

    class HStoreExtension

    安装 hstore 扩展,并设置连接来解释 hstore 数据,以便在后续迁移中使用。

    class TrigramExtension

    安装 pg_trgm 扩展。

    UnaccentExtension

    class UnaccentExtension

    安装 unaccent 扩展。

    Managing collations using migrations

    New in Django Development version.

    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 , TextField, and their subclasses.

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

    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

    PostgreSQL 9.6 only supports the 'libc' provider.

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

    并发索引操作

    PostgreSQL 支持 CREATE INDEXDROP INDEX 语句中的 CONCURRENTLY 选项,以增加和删除索引而不锁定写入。这个选项对于在实际生产的数据库中添加或删除索引非常有用。

    class AddIndexConcurrently(model_name, index)

    就像 一样,但是使用 CONCURRENTLY 选项创建索引。这在使用这个选项时有一些注意事项,参见 PostgreSQL 关于并发建立索引的文档

    class RemoveIndexConcurrently(model_name, name)

    就像 一样,但是使用 CONCURRENTLY 选项来删除索引。这在使用这个选项时有一些注意事项,请看 PostgreSQL 文档

    在事务中不支持 选项(见 )。