我有一个模型 project_phase :
from django.db import models
from django.utils import simplejson
from core.models import pmo_review_task
引用 pmo_review_task (因为它在其save ovewrite中创建了pmo_review_task)
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
from core.models import sc_review_task
引用引用project_phase的 sc_review_task (因为它在save ovewrite中创建了project_phase)
from django.db import models
from core.models import project_phase
所以最终 project_phase 导入 pmo_review_task 导入 sc_review_task 导入 project_phase ,我猜它会以某种方式循环生成这个错误:
Unhandled exception in thread started by <bound method Command.inner_run of <django.core.management.commands.runserver.Command object at 0x010ACFB0>>
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 88, in inner_run
self.validate(display_num_errors=True)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "C:\Python27\lib\site-packages\django\core\management\validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 146, in get_app_errors
self._populate()
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 64, in _populate
self.load_app(app_name)
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in import_module
__import__(name)
File "C:\work\Portman\core\models\__init__.py", line 4, in <module>
from pmo_review_task import pmo_review_task
File "C:\work\Portman\core\models\pmo_review_task.py", line 5, in <module>
from core.models import sc_review_task
File "C:\work\Portman\core\models\sc_review_task.py", line 3, in <module>
from core.models import project_phase
File "C:\work\Portman\core\models\project_phase.py", line 4, in <module>
from core.models import pmo_review_task
ImportError: cannot import name pmo_review_task
我该如何克服这个?
答案 0 :(得分:19)
两种方式:
使用专为延迟模型导入设计的get_model
django.db.models
函数。:
project_phase = get_model('core', 'project_phase')
我更喜欢第二种,但两种方法都可以。
答案 1 :(得分:7)
在project_phase
方法中导入save
。
只要执行代码,就会调用导入。
如果它位于全局模块命名空间(顶部),则会立即调用它,并且您将描述循环导入问题,因为一个文件导入另一个导入原始文件的文件。
如果将问题导入语句放在函数中,则在导入文件时会调用/不调用它。
import foo # executed upon importing this file.
def import_foo_when_called():
import foo # only executed when function is called, thus no problems when
# another module imports this file.
答案 2 :(得分:2)
Django 1.9及以上
在django.db.models中的get_model()
已在1.9中删除。
使用django.apps.get_model()
类似的问题: What is the equivalent of django.db.models.loading.get_model() in Django 1.9?
如果您只是用它来创建外键,请在引号中使用应用程序标签。
而不是from core.models import project_phase
做
models.ForeignKey("core.project_phase")