Django迁移-在RunPython函数中获取当前应用程序名称

Django迁移-在RunPython函数中获取当前应用程序名称,django,django-migrations,Django,Django Migrations,我的一个迁移有一个附加功能,可以使用RunPython运行。此消息的目的只是向用户显示一条快乐的消息。唯一的问题是,我需要显示一个应用程序名,在其中创建并运行当前迁移。这有可能吗 我的代码: from django.db import migrations, models import django.db.models.deletion def happy_message(apps, schema_editor): print('A happy message from migrat

我的一个迁移有一个附加功能,可以使用
RunPython
运行。此消息的目的只是向用户显示一条快乐的消息。唯一的问题是,我需要显示一个应用程序名,在其中创建并运行当前迁移。这有可能吗

我的代码

from django.db import migrations, models
import django.db.models.deletion


def happy_message(apps, schema_editor):
    print('A happy message from migration inside app named {}')


class Migration(migrations.Migration):

    operations = [
        migrations.AddField(
            model_name='mymodel',
            name='rank_no',
            field=models.IntegerField(null=True),
        ),
        migrations.RunPython(
            happy_message,
            migrations.RunPython.noop
        ),
    ]

如果您使用的是经典的Django文件体系结构,那么您的迁移文件应该位于
project\u dir/app\u dir/migrations/0001\u migration\u file.py

然后,您只需获取应用程序目录名:

从os.path导入basename,dirname
def happy_消息(应用程序、架构编辑器):
app_name=basename(dirname(dirname(_文件__)))
打印(来自名为{app_name}的应用程序内部迁移的快乐消息)

您可以对自定义
RunPython
code
(和
reverse\u code
)属性进行猴子补丁,以支持额外的参数
app\u标签

from django.db import migrations


class AppAwareRunPython(migrations.RunPython):

    # MonkeyPatch the `code` call with a lambda that add an extra argument `app_label`
    def database_forwards(self, app_label, schema_editor, from_state, to_state):
        mp_code = self.code
        self.code = lambda apps, se: mp_code(apps, se, app_label)
        super().database_forwards(app_label, schema_editor, from_state, to_state)

    # Same for backwards if you want to display message when unapplying the migration
    def database_backwards(self, app_label, schema_editor, from_state, to_state):
        if self.reverse_code:
            mp_reverse_code = self.reverse_code
            self.reverse_code = lambda apps, se: mp_reverse_code(apps, se, app_label)
        super().database_backwards(app_label, schema_editor, from_state, to_state)

    # Add the etra argument to noop
    @staticmethod
    def noop(apps, schema_editor, app_label=None):
        migrations.RunPython.noop(apps, schema_editor)


# This function can't be used with classic RunPython unless you put `app_label=None` and test its value
def happy_message(apps, schema_editor, app_label):
    print(f'A happy message from migration inside app named {app_label}')


class Migration(migrations.Migration):

    operations = [
        AppAwareRunPython(happy_message, AppAwareRunPython.noop),
    ]

您可以使用可用的标志选项命名您正在进行的迁移。不过,它似乎有点不成熟。是的,但我还没有找到从RunPython中从迁移对象中检索“app_label”属性的方法^^