How to access model's class level variable in data migration?

荒凉一梦 提交于 2019-12-06 02:38:14

问题


Here is my model.

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

Here is my data migration:

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

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']

回答1:


You should be able to import the model

from my_app.models import Poll

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




回答2:


I think you can't access model method in migration. I found the answer here How to call a static methods on a django model class during a south migration



来源:https://stackoverflow.com/questions/32102931/how-to-access-models-class-level-variable-in-data-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!