django迁移如何引用模型内部的类

时间:2017-11-09 07:49:58

标签: django django-migrations

我希望参考一个内部课程' Code'在模型'评估'。基本上这两个选项都不起作用(选项:1)

code = apps.get_model('my_project', 'Evaluation.Code') 

OR(选项:2)

evaluation = apps.get_model('my_project', 'Evaluation')
code = evaluation.Code

选项:1抛出这个错误:

grzsqrrel@grzsqrreld:~/PycharmProjects/my_project/my_project$ python manage.py migrate
    local_settings.py not found
    Operations to perform:
    Apply all migrations: admin, auth, contenttypes, django_cron, sessions, my_project_app
    Running migrations:
    Applying my_project_app.0002_load_items...Traceback (most recent call last):
    File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
    File "/home/grzsqrrel/.virtualenvs/my_project/lib/python3.5/site-packages/django/core/management/__init__.py", line 363,...
    File "/home/grzsqrrel/.virtualenvs/my_project/lib/python3.5/site-packages/django/db/migrations/operations/special.py", line 193, in database_forwards
    self.code(from_state.apps, schema_editor)
    File "/home/grzsqrrel/PycharmProjects/my_project/my_project/my_project_app/migrations/0002_load_items.py", line 7, in load_data
    code = evaluation.Code
    AttributeError: type object 'Evaluation' has no attribute 'Code'

models.py:

class Evaluation(models.Model):
    class Code:

0002_load_items.py

def load_data(apps, schema_editor):
    evaluation = apps.get_model('my_project', 'Evaluation')
    code = evaluation.Code

class Migration(migrations.Migration):
    dependencies = [
        ('my_project', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(load_data)
    ]   

修复是什么?谢谢。

1 个答案:

答案 0 :(得分:0)

事实证明,答案在其他地方。由于我不是使用内部类创建对象,我可以使用常规导入。

from django.db import migrations
from my_project.models import Evaluation

def load_data(apps, schema_editor):
    evaluation = apps.get_model('my_project', 'Evaluation')
    code = Evaluation.Code
    my_model.objects.create(item_code=code.COURSES_TAUGHT)