如何在数据迁移中访问模型的类级别变量? [英] How to access model's class level variable in data migration?

查看:94
本文介绍了如何在数据迁移中访问模型的类级别变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模型。

Poll(models.Model):
   title = models.CharField(max_length=1024)
   MY_VAR = ['my_class_level_attribute'] # I want to access this

是我的数据迁移:

def my_func(apps, schema_editor):
    Poll = apps.get_model('my_app', 'Poll')
    print Poll.MY_VAR


class Migration(migrations.Migration):

    dependencies = [
        ('webmerge', '0012_previous_migration'),
    ]

    operations = [
        migrations.RunPython(my_func)
    ]

print Poll.MY_VAR 给出属性错误。我认为问题可能在于 get_model 在数据迁移中的性能如何,因为以下行在Django shell中成功完成:

The line print Poll.MY_VAR gives an attribute error. I think the issue might is in how get_model performs within a data migration because the following lines succeed in a Django shell:

In [2]: from django.apps import apps
In [3]: Poll = apps.get_model('my_app', 'Poll')
In [4]: Poll.MY_VAR
Out[4]:  ['my_class_level_attribute']


推荐答案

您应该能够从my_app.models import Poll $ b中导入模型

You should be able to import the model

from my_app.models import Poll

如果这样做,则不应删除投票模型或 MY_VAR 属性,否则您的迁移将停止工作。

If you do this, you shouldn't delete the Poll model or the MY_VAR attribute, otherwise your migrations will stop working.

这篇关于如何在数据迁移中访问模型的类级别变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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