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

问题描述 投票:0回答:1

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

CREATE EXTENSION ltree;

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

django postgresql-9.3 django-migrations ltree
1个回答
0
投票

我知道这很长时间没有答案,也许现在你已经找到了答案。但是我发帖以防万一有人从中得到一些帮助。

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

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

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.