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

Phy*_*nte 5 python django django-migrations

我想在迁移结束时包含对许多原始 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', 'triggers']

    for folder in folders:
        load_raw_sql(folder)


class Migration(migrations.Migration):
    dependencies = [
        ('app1', '0001_squashed_0018_auto_20150616_0708'),
    ]

    operations = [
        migrations.RunPython(load_sql),
    ]
Run Code Online (Sandbox Code Playgroud)

我们正在使用 PostGreSQL。预先感谢您的回答。

Gre*_*reg 5

我认为很明显,一个名为RunPythoner 的操作可以运行 python 代码,但简短的答案是肯定的,您可以在操作中做任何您想做的事情RunPython

要考虑的主要问题是,您编写的代码需要在将来继续工作(或者直到您压缩迁移),因为每次运行migrate或时makemigrations,所有以前的迁移都将用于派生数据库的当前状态。