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

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

我的一次迁移具有使用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 django-migrations
2个回答
2
投票

您可以修补自定义codereverse_code(和RunPython)属性,以支持额外的参数app_label

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),
    ]

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}')
© www.soinside.com 2019 - 2024. All rights reserved.