【问题标题】:Django 1.9: Should I avoid importing models during `django.setup()`?Django 1.9:我应该避免在 `django.setup()` 期间导入模型吗?
【发布时间】:2016-03-15 11:15:07
【问题描述】:

将我的应用程序移植到 django 1.9,我得到了可怕的 django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet

基本上我的堆栈跟踪是:

  manage.py
    execute_from_command_line(sys.argv)
  django/core/management:352, in execute_from_command_line
    utility.execute()
  django/core/management/__init__.py:326, in execute
    django.setup()
  django/__init__.py:18, in setup
    apps.populate(settings.INSTALLED_APPS)
  django/apps/registry.py:85, in populate
    app_config = AppConfig.create(entry)
  django/apps/config.py:90, in create
    module = import_module(entry)
  python2.7/importlib/__init__.py:37, in import_module
    __import__(name)
  myapp/mylib/__init__.py:52, in <module>
    from django.contrib.contenttypes.models import ContentType   #<= The important part
  django/contrib/contenttypes/models.py:159, in <module>
    class ContentType(models.Model):
  django/db/models/base.py:94, in __new__
    app_config = apps.get_containing_app_config(module)
  django/apps/registry.p:239, in get_containing_app_config
    self.check_apps_ready()
  django/apps/registry.py:124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

我的主要问题:

我应该在我的 django 应用程序的__init__.py 中导入我的模型吗?

它似乎触发了django.models.ModelBase 元类,在创建模型之前检查应用是否准备就绪。

【问题讨论】:

    标签: python django django-models django-1.9


    【解决方案1】:

    我应该在我的 django 应用程序的__init__.py 中导入我的模型吗?

    不,您不得在任何已安装应用的__init__.py 文件中导入任何模型。这在 1.9 中不再可能。

    来自release notes

    所有模型都需要在已安装的应用程序中定义,或者 声明一个显式的 app_label。此外,不可能 在加载应用程序之前导入它们。 特别是它 无法在根包中导入模型 应用程序。

    【讨论】:

      猜你喜欢
      • 2018-09-09
      • 2020-11-08
      • 2011-04-06
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 2018-12-25
      相关资源
      最近更新 更多