【问题标题】:nested import of models in django 1.7 and python 2.7在 django 1.7 和 python 2.7 中嵌套导入模型
【发布时间】:2015-01-04 12:40:42
【问题描述】:

这个问题的标题可能会令人困惑。我不知道应该给这个问题起什么标题。

我有两个模型文件 ==> 应用程序 a 中的 models.py 和应用程序 b 中的 models.py models.py 在应用程序 a 中有 class A models.py 在应用 b 中有 class B

两个类都扩展了django.db.models.Model,即这些类正在制作数据库表

我想 import class A from models.py from app a 导入 class B from models.py in app b.

我想说两个类都在互相使用。

如果我这样编码: 应用程序中的models.py ==>

from b.models import B

应用 b 中的models.py ==>

from a.models import A

然后我收到未定义 B 的导入错误。

如何在两个文件中导入两个类?

【问题讨论】:

  • 您是否已将应用 B 添加到您的 settings.py 中?
  • 是的,所有其他事情都是正确的。我想知道两个模型如何同时相互交互的一件事。

标签: python django python-2.7 django-1.7


【解决方案1】:

您可以在不导入模型的情况下创建外键。而不是模型类传递一个带有应用程序名称和模型名称的字符串。见the docs for ForeignKey

class B(models.Model):

    a = models.ForeignKey('a.A')

如果您想在代码中的某处访问此类模型,请将其导入函数中:

class B(models.Model):

    def some_method(self):
        from a.models import A
        ...

【讨论】:

    【解决方案2】:

    这是一个循环依赖问题。你检查Circular dependency in Python答案。

    简而言之,您应该尝试更改您的班级组织以防止这种情况发生,或者您可以在函数中使用导入来避免导入错误。

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 2015-04-04
      • 2020-06-11
      • 2020-01-06
      相关资源
      最近更新 更多