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

How install a extension in postgresql before creating the models in django?

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

CREATE EXTENSION ltree;

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

我知道这个问题很长时间都没有答案,也许现在您已经找到答案了。但我发帖是为了防止有人从中得到一点帮助。

对于 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_before 的使用。它与 dependencies 正好相反。或者,您可以将此迁移作为第一个迁移,然后使用 dependencies.

加载所有其他迁移

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

ALTER ROLE user_name superuser;
# create the extension and then remove the superuser privileges.
ALTER ROLE user_name nosuperuser;

对于 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)
]

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

希望对您有所帮助。

您还可以在模板数据库上安装扩展,当创建新数据库时(如 运行 测试时),新数据库将复制该模板并包含扩展。

psql -d template1 -c 'create extension if not exists hstore;'