问题
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