Django 模型如何修复循环导入错误?

用户15867719

我阅读了错误的解决方案(写入import而不是from ...),但我认为它不起作用,因为我有一个复杂的文件夹结构。

目录结构

测验/模型.py

import apps.courses.models as courses_models


class Quiz(models.Model):
    lesson = models.ForeignKey(courses_models.Lesson, on_delete=models.DO_NOTHING)  # COURSE APP MODEL IMPORTED

课程/模型.py

import apps.quiz.models as quiz_models


class Lesson(models.Model):
   ...

class UserCompletedMaterial(models.Model):
   ...
   lesson = models.ForeignKey(Lesson)
   quiz = models.ForeignKey(quiz_models.Quiz)  # QUIZ APP MODEL IMPORTED


你怎么看我就是不能把它放在一起或别的什么..
因为我认为UserCompletedMaterial模型是courses应用程序的一部分

威廉·范·翁塞姆

两个模型相互引用,因此这意味着为了解释前者,我们需要后者,反之亦然。

Django however has a solution to this: you can not only pass a reference to the class as target model for a ForeignKey (or another relation like a OneToOneField or a ManyToManyField), but also through a string.

In case the model is in the same application, you can use a string 'ModelName', in case the model is defined in another installed app, you can work with 'app_name.ModelName'. In this case, we thus can remove the circular import with:

# do not import the `courses.models

class Quiz(models.Model):
    lesson = models.ForeignKey(
        'courses.Lesson',
        on_delete=models.DO_NOTHING
    )
    # …

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章