Django模型如何修复循环导入错误? [英] Django models how to fix circular import error?

查看:81
本文介绍了Django模型如何修复循环导入错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I read about a solution for the error (write import instead of from ...) but it doesn't work I think because I have a complex folder structure.

目录结构

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

courses/models.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 app

推荐答案

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

Both models refer to each other, and this thus means that in order to interpret the former, we need the latter and vice versa.

但是Django有一个解决方案:您不仅可以将对 class 的引用作为 ForeignKey target 模型传递(或另一个关系,例如 OneToOneField ManyToManyField ),也可以通过 string 来实现.

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.

如果模型在同一应用程序中,则可以使用字符串' ModelName ',如果模型是在另一个所安装的模型中定义的应用,则可以使用' app_name . ModelName '.因此,在这种情况下,我们可以使用以下命令删除循环导入:

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
    )
    # …

这篇关于Django模型如何修复循环导入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆