小编Phy*_*nte的帖子

migrations.RunPython 可以运行任意 python 代码吗?

我想在迁移结束时包含对许多原始 SQL 文件(函数、触发器...)的处理。

我想编写自己的特殊操作,但有人告诉我改用django.db.migrations.RunPython()命令,并将一些 django.db.migrations.RunSQL() 命令放在被调用的函数中。

由于 RunPython() 需要一个带有 2 个实例(一个 App 和一个 SchemaEditor)的可调用函数,我严重怀疑(我稍微回顾了一下源代码)我可以用纯 python 代码调用一个函数,它似乎只能执行 ORM 操作。我应该在 RunPython 中使用execute_from_command_line()吗?或者说这条路注定会失败?还是做事不好?

from __future__ import unicode_literals
from django.db import migrations

def load_sql(apps, schema_editor):

    from os.path import normpath, dirname, isfile, join
    from os import listdir

    sql_folder_path = '/backoffice/sql/'

    def load_raw_sql(folder_inside):
        folder_path = join(sql_folder_path, folder_inside)
        sql_files = [join(folder_path, f) for f in listdir(folder_path) if isfile(join(folder_path, f))]
        for sql_file in sql_files:
            with open(sql_file, 'r') as g:
                migrations.RunSQL(g.read())

    folders = ['functions', 'index', …
Run Code Online (Sandbox Code Playgroud)

python django django-migrations

5
推荐指数
1
解决办法
3447
查看次数

标签 统计

django ×1

django-migrations ×1

python ×1