我有两个应用程序……我们称它们为tiger
和bird
。最初,我在tiger
应用中使用了bird
的模型。这就是我在bird/models.py
中进行导入的方式:
from django.db import models
from tiger.models import TigerClass, AnotherTigerClass
效果很好。我将TigerClass和OtherTigerClass导入到bird
应用中没有问题。
现在,我也想做相反的事情。因此,在tiger
应用中,我想从bird
应用中导入模型。据我在手册中可以找到的,对此没有任何限制,我应该能够使用相同的语法。这就是我在tiger/models.py
中所做的:
from django.db import models
from bird.models import BirdClass
但是,当我这样做时,我的应用程序会抛出一个非常奇怪的错误:
web_1 | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fac830d1730>
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
web_1 | fn(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run
web_1 | autoreload.raise_last_exception()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception
web_1 | raise _exception[1]
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute
web_1 | autoreload.check_errors(django.setup)()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
web_1 | fn(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
web_1 | apps.populate(settings.INSTALLED_APPS)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
web_1 | app_config.import_models()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
web_1 | self.models_module = import_module(models_module_name)
web_1 | File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
web_1 | return _bootstrap._gcd_import(name[level:], package, level)
web_1 | File "<frozen importlib._bootstrap>", line 994, in _gcd_import
web_1 | File "<frozen importlib._bootstrap>", line 971, in _find_and_load
web_1 | File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
web_1 | File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
web_1 | File "<frozen importlib._bootstrap_external>", line 678, in exec_module
web_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
web_1 | File "/code/tiger/models.py", line 3, in <module>
web_1 | from bird.models import ProcessType
web_1 | File "/code/bird/models.py", line 2, in <module>
web_1 | from tiger.models import TigerClass, AnotherTigerClass
web_1 | ImportError: cannot import name 'TigerClass'
所以现在突然之间,它抱怨无法将TigerClass导入到bird
应用程序中。奇怪的是,以前它还可以正常工作!我在tiger/models.py
文件中添加了一个新的import语句,但是现在bird/models.py
文件中有一个错误。我茫然为什么这是一个问题。我已经对名称进行了三重检查,从其他应用程序复制了相同的语句,并尝试在同一应用程序中导入不同的类...所有这些都没有任何更改。
答案 0 :(得分:0)
您正处于循环中,您正在尝试导入鸟类中的老虎模型和老虎中的鸟类模型。一种解决方案是对关系使用模型的字符串表示形式,在这种情况下,您无需导入。 或导入模型文件不做循环导入。