检测和纠正循环进口

时间:2014-05-19 19:40:13

标签: python django

所以,这是我上周要求的扩展(Why do I need to import a class within this class, instead of at the top of the file?),但经过大量调试后,我觉得这可能需要一个新问题。

我有许多模块,都有导入。我怀疑可能存在循环导入,但我无法找到它。

这是奇怪的事情:

在一个models.py文件中,我有:

from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from heythere.models import Notification as HeyThere
from heythere.models import NotificationManager as HeyThereManager
from django.contrib.auth.models import User

然后是一些模型定义,包括一个方法:

def to_user(self):
    try:
        return User.objects.get(username=str(self.username))
    except ObjectDoesNotExist:
        return None

又向下一点:

from ownership.apps.Assets.models import Item

当它是这样时,我得到AttributeError: 'NoneType' object has no attribute 'objects'(指用户)。所以它设置为None,不知何故,而不是提出global name XXX is not defined

但是,我尝试在导入后立即访问用户:

me = User.objects.get(username='xxxx')
print me

在运行runserver时正确打印,因此我知道它可以在那里访问用户,但随后给了我错误消息ImportError: cannot import name Item。如何简单地访问模型导致导入错误? (FWIW,Item确实与User有许多FK关系)

是什么给出的?

包含User.objects.get()时的回溯:

  File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/utils/autoreload.py", line 93, in wrapper
    fn(*args, **kwargs)
  File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 101, in inner_run
    self.validate(display_num_errors=True)
  File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/core/management/base.py", line 310, in validate
    num_errors = get_validation_errors(s, app)
  File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/core/management/validation.py", line 34, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/db/models/loading.py", line 196, in get_app_errors
    self._populate()
  File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/db/models/loading.py", line 78, in _populate
    self.load_app(app_name)
  File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/db/models/loading.py", line 99, in load_app
    models = import_module('%s.models' % app_name)
  File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
    __import__(name)
  File "/Users/xxxxx/code/ownership/ownership/apps/Assets/models.py", line 12, in <module>
    import permissions
  File "/Users/xxxxx/code/ownership/ownership/apps/Assets/permissions.py", line 4, in <module>
    from ownership.apps.Shared.models import Person
  File "/Users/xxxxx/code/ownership/ownership/apps/Shared/models.py", line 87, in <module>
    from ownership.apps.Assets.models import Item
ImportError: cannot import name Item

没有(代码应该如何工作):

Environment:


Request Method: POST
Request URL: http://localhost:8000/application/new

Django Version: 1.6.1
Python Version: 2.7.2
Installed Applications:
('suit',
 'south',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.redirects',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'rest_framework',
 'ldap_sync',
 'crispy_forms',
 'ownership.apps.Catalog',
 'ownership.apps.Assets',
 'ownership.apps.Shared',
 'ownership.libs.display',
 'django_tables2',
 'haystack',
 'autocomplete_light',
 'reversion',
 'heythere',
 'polymorphic',
 'django_extensions',
 'debug_toolbar')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
 'django.middleware.transaction.TransactionMiddleware',
 'reversion.middleware.RevisionMiddleware',
 'ownership.libs.shibboleth.CustomHeaderMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware')


Traceback:
File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/xxxxx/code/ownership/ownership/apps/Assets/crud_views.py" in connect_create_view
  48.             return subview.as_view()(request, model_name=model_name)
File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/views/generic/base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)
File "/Users/xxxxx/.virtualenvs/ownership/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
  87.         return handler(request, *args, **kwargs)
File "/Users/xxxxx/code/ownership/ownership/apps/Assets/crud_views.py" in post
  280.                 create_new_asset_notification(request, new_item)
File "/Users/xxxxx/code/ownership/ownership/apps/Shared/views.py" in create_new_asset_notification
  123.                 send_email(request, subject, body, owner.to_user().email, )
File "/Users/xxxxx/code/ownership/ownership/apps/Shared/models.py" in to_user
  52.             return User.objects.get(username=str(self.username))

Exception Type: AttributeError at /application/new
Exception Value: 'NoneType' object has no attribute 'objects'

1 个答案:

答案 0 :(得分:0)

请注意我的堆栈跟踪:

 File "/Users/xxxxx/code/ownership/ownership/apps/Assets/models.py", line 12, in <module>
    import permissions   File "/Users/xxxxx/code/ownership/ownership/apps/Assets/permissions.py", line 4, in <module>
    from ownership.apps.Shared.models import Person   File "/Users/xxxxx/code/ownership/ownership/apps/Shared/models.py", line 87, in <module>
    from ownership.apps.Assets.models import Item

Assets/models.py正在导入permissions
Permissions正在导入Shared.models.Person
Shared/models正在导入Assets.models.Item

这是一个循环导入。

通过将from django.contrib.auth.models import User移动到Person模型内部来纠正此问题。我不太明白为什么 - 如果有人想在我接受我自己的答案之前详细说明并提供更好的解释,请做。