在 Django 中创建模型之前,如何在 postgresql 中安装扩展?

mam*_*mcx 3 django ltree postgresql-9.3 django-migrations

使用 django 1.8 + Postgres 9+,我有带有自定义 PG 数据类型(如 ltree)的模型。从零创建数据库失败,因为

CREATE EXTENSION ltree;
Run Code Online (Sandbox Code Playgroud)

不被执行。我尝试进行空迁移,但在模型创建运行。是否存在在模型创建之前运行 sql 的方法?

San*_*ana 9

我知道这已经很久没有答案了,也许现在您已经找到了答案。但我发帖只是以防万一有人从中得到一点帮助。

对于 Postgres 中可用的扩展

如果扩展是 Postgres 可用的默认设置之一,那么您可以简单地创建第一个迁移,然后加载其他迁移。

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.postgres.operations import HStoreExtension

from django.db import migrations


class Migration(migrations.Migration):

    run_before = [
        ('some_app_that_requires_hstore', '0001_initial'),
    ]

    operations = [
        HStoreExtension(),
    ]
Run Code Online (Sandbox Code Playgroud)

注意使用run_before. 它与 完全相反dependencies。或者,您可以将此迁移作为第一个迁移,并在此之后使用dependencies.

如果此迁移由于权限问题而无法创建扩展,那么您可以简单地在 Postgres 中使用superusernosuperuser来临时为当前用户提供权限以运行迁移,例如:

ALTER ROLE user_name superuser;
# create the extension and then remove the superuser privileges.
ALTER ROLE user_name nosuperuser;
Run Code Online (Sandbox Code Playgroud)

对于 Postgres 中没有的第三方扩展

对于第三方扩展,您可以使用 run_python,为您加载扩展,例如:

from django.db import migrations


def create_third_party_extension(apps, schema_editor):
    schema_editor.execute("CREATE EXTENSION my_custom_extension;")


def drop_third_party_extension(apps, schema_editor):
    schema_editor.execute("DROP EXTENSION IF EXISTS my_custom_extension;")


class Migration(migrations.Migration):

    dependencies = [
        ('venues', '0001_auto_20180607_1014'),
    ]

    operations = [
        migrations.RunPython(create_third_party_extension, reverse_code=drop_third_party_extension, atomic=True)
]
Run Code Online (Sandbox Code Playgroud)

或者,您可以将它们作为部署脚本的一部分而不是迁移。

我希望这有帮助。