gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:13:02 24 4
gpt4 key购买 nike

我的一个迁移具有使用 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
),
]

最佳答案

您可以修补 code (和 reverse_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),
]

关于Django 迁移 - 在 RunPython 函数中获取当前应用程序名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55530160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com