Django迁移RunPython无法调用模型方法 [英] Django migrations RunPython not able to call model methods

查看:82
本文介绍了Django迁移RunPython无法调用模型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RunPython 方法创建数据迁移。但是,当我尝试在对象上运行方法时,都没有定义。是否可以使用 RunPython 调用在模型上定义的方法?

I'm creating a data migration using the RunPython method. However when I try to run a method on the object none are defined. Is it possible to call a method defined on a model using RunPython?

推荐答案

模型方法在迁移(包括数据迁移)中不可用。

Model methods are not available in migrations, including data migrations.

但是有解决方法,应该与调用模型方法非常相似。您可以在迁移过程中定义模拟您要使用的模型方法的函数。

However there is workaround, which should be quite similar to calling model methods. You can define functions inside migrations that mimic those model methods you want to use.

如果您有此方法:

class Order(models.Model):
    '''
    order model def goes here
    '''

    def get_foo_as_bar(self):
        new_attr = 'bar: %s' % self.foo
        return new_attr

您可以在迁移脚本中编写函数,例如:

You can write function inside migration script like:

def get_foo_as_bar(obj):
    new_attr = 'bar: %s' % obj.foo
    return new_attr


def save_foo_as_bar(apps, schema_editor):
    old_model = apps.get_model("order", "Order")

    for obj in old_model.objects.all():
        obj.new_bar_field = get_foo_as_bar(obj)
        obj.save()

然后在迁移中使用它:

class Migration(migrations.Migration):

    dependencies = [
        ('order', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(save_foo_as_bar)
    ]

这样迁移将起作用。代码会有所重复,但这没关系,因为在应用程序的特定状态下,数据迁移应该是一次操作。

This way migrations will work. There will be bit of repetition of code, but it doesn't matter because data migrations are supposed to be one time operation in particular state of an application.

这篇关于Django迁移RunPython无法调用模型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆