gpt4 book ai didi

python - django 模型递归导入 - 如何解决

转载 作者:太空狗 更新时间:2023-10-29 20:33:53 25 4
gpt4 key购买 nike

我有一个模型project_phase:

    from django.db import models
from django.utils import simplejson
from core.models import pmo_review_task

它引用了pmo_review_task(因为它在它的保存覆盖中创建了一个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

它引用了 sc_review_task,它引用了 project_phase(因为它在其保存覆盖中创建了一个 project_phase)

from django.db import models
from core.models import project_phase

所以它结束了 project_phase imports pmo_review_task imports sc_review_task imports 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

我该如何克服这个问题?

最佳答案

两种方式:

  1. 在方法中导入模型(如@YujiTomita 所建议)。
  2. 使用 django.db.models 中的 get_model 函数,该函数专为惰性模型导入而设计。

    project_phase = get_model('core', 'project_phase')

我更喜欢第二种,但是两种方法都可以。

关于python - django 模型递归导入 - 如何解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9324554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com