代码之家  ›  专栏  ›  技术社区  ›  Grizzled Squirrel

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

  •  1
  • Grizzled Squirrel  · 技术社区  · 8 年前

    我希望引用模型“Evaluation”下的内部类“Code”。基本上这两个选项都不起作用(选项:1)

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

    或(选项: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'
    

    模型。py:

    class Evaluation(models.Model):
        class Code:
    

    0002_load_项目。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 回复  |  直到 8 年前
        1
  •  0
  •   Grizzled Squirrel    8 年前

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

    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)