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

时间:2019-04-05 07:20:26

标签: 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 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
        ),
    ]

2 个答案:

答案 0 :(得分:1)

您可以对自定义code的{​​{1}}(和reverse_code)属性进行猴子补丁,以支持额外的参数RunPython

app_label

答案 1 :(得分:0)

如果您使用的是经典的Django文件体系结构,则您的迁移文件应位于project_dir/app_dir/migrations/0001_migration_file.py中。

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

from os.path import basename, dirname

def happy_message(apps, schema_editor):
    app_name = basename(dirname(dirname(__file__)))
    print(f'A happy message from migration inside app named {app_name}')