我阅读了错误的解决方案(写入import
而不是from ...
),但我认为它不起作用,因为我有一个复杂的文件夹结构。
目录结构
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
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] 删除。
我来说两句