所有这些 操作 都可以从 django.contrib.postgres.operations 模块中获得。
你可以使用迁移文件在数据库中创建一个 PostgreSQL 扩展。这个例子创建了一个 hstore 扩展,但同样的原理也适用于其他扩展。
在涉及到 HStoreField 的第一个 CreateModel 或 AddField 操作之前,通过添加 HStoreExtension 操作的迁移,在 PostgreSQL 中设置 hstore 扩展。例如:
from django.contrib.postgres.operations import HStoreExtension
class Migration(migrations.Migration):
...
operations = [
HStoreExtension(),
...
]
如果扩展名已经存在,该操作会跳过添加。
对于大多数扩展来说,这需要一个具有超级用户权限的数据库用户。如果 Django 数据库的用户没有相应的权限,你就必须在 Django 迁移之外用一个有权限的用户创建扩展。在这种情况下,连接到你的 Django 数据库,并运行查询 CREATE EXTENSION IF NOT EXISTS hstore;。
在旧版本中,没有检查扩展是否预先存在。
CreateExtension¶如果你需要使用你的操作系统提供的特定字节序来过滤或排序一个列,但 PostgreSQL 没有提供,你可以使用迁移文件来管理数据库中的字节序。然后,这些字节序可以在 CharField、TextField 以及它们的子类上使用 db_collation 参数。
例如,为德国电话簿的排序创建一个字节序:
from django.contrib.postgres.operations import CreateCollation
class Migration(migrations.Migration):
...
operations = [
CreateCollation(
'german_phonebook',
provider='icu',
locale='und-u-ks-level2',
),
...
]
CreateCollation(name, locale, *, provider='libc', deterministic=True)¶用给定的 name、locale 和 provider 创建一个字节序。
将 deterministic 参数设置为 False 以创建一个非确定的字节序,例如用于不区分大小写的过滤。
RemoveCollation(name, locale, *, provider='libc', deterministic=True)¶移除名为 name 的字节序。
当反查时,这是用提供的 locale、provider 和 deterministic 参数创建一个字节序。因此,需要 locale 来使这个操作可逆。
限制条件
只有 PostgreSQL 12+ 支持非确定的的字节序。
PostgreSQL 支持 CREATE INDEX 和 DROP INDEX 语句中的 CONCURRENTLY 选项,以增加和删除索引而不锁定写入。这个选项对于在实际生产的数据库中添加或删除索引非常有用。
AddIndexConcurrently(model_name, index)¶就像 AddIndex 一样,但是使用 CONCURRENTLY 选项创建索引。这在使用这个选项时有一些注意事项,参见 PostgreSQL 关于并发建立索引的文档 。
RemoveIndexConcurrently(model_name, name)¶就像 RemoveIndex 一样,但是使用 CONCURRENTLY 选项来删除索引。这在使用这个选项时有一些注意事项,请看 PostgreSQL 文档 。
注解
在事务中不支持 CONCURRENTLY 选项(见 非原子性迁移)。
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.
AddConstraintNotValid(model_name, constraint)¶Like AddConstraint, but avoids
validating the constraint on existing rows.
ValidateConstraint(model_name, name)¶Scans through the table and validates the given check constraint on existing rows.
注解
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.
12月 13, 2021