Django 1.8 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

在进行 Django 日常开发时,经常会建立一个独立的 PY 文件用来测试写好的方法.

# mysite/main.py
# -*- coding:utf-8 -*-

from deploy.getInfo import *
from getRunTime import *

def main():
    # 获取域
    print getDomain()
    # 获取域名对应规则
    print getDomainRewrite("1")

if __name__ == ‘__main__‘:
    main()

启动 Django 时报错

Traceback (most recent call last):
  File "E:\MyEclipse_work\ops\deploy\main.py", line 35, in <module>
    main()
  File "E:\MyEclipse_work\ops\deploy\main.py", line 12, in main
    print getDomain()
  File "E:\MyEclipse_work\ops\deploy\deploy\getInfo.py", line 10, in getDomain
    return json.dumps(list(deploy.objects.filter().values("domain_id__domain_name","domain_id")))
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\db\models\query.py", line 640, in values
    return self._clone(klass=ValuesQuerySet, setup=True, _fields=fields)
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\db\models\query.py", line 992, in _clone
    c._setup_query()
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\db\models\query.py", line 1169, in _setup_query
    self.query.add_fields(self.field_names, True)
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\db\models\sql\query.py", line 1660, in add_fields
    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m)
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\db\models\sql\query.py", line 1443, in setup_joins
    names, opts, allow_many, fail_on_missing=True)
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\db\models\sql\query.py", line 1347, in names_to_path
    field, model, _, _ = opts.get_field_by_name(name)
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\db\models\options.py", line 406, in get_field_by_name
    cache = self.init_name_map()
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\db\models\options.py", line 435, in init_name_map
    for f, model in self.get_all_related_m2m_objects_with_model():
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\db\models\options.py", line 520, in get_all_related_m2m_objects_with_model
    cache = self._fill_related_many_to_many_cache()
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\db\models\options.py", line 534, in _fill_related_many_to_many_cache
    for klass in self.apps.get_models():
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\utils\lru_cache.py", line 101, in wrapper
    result = user_function(*args, **kwds)
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\apps\registry.py", line 168, in get_models
    self.check_models_ready()
  File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\apps\registry.py", line 131, in check_models_ready
    raise AppRegistryNotReady("Models aren‘t loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren‘t loaded yet.

最后的报错为: django.core.exceptions.AppRegistryNotReady: Models aren‘t loaded yet.

报错信息来自于 registry.py 的断言.

File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\apps\registry.py", line 131, in check_models_ready
  raise AppRegistryNotReady("Models aren‘t loaded yet.")

因此查看 C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\apps\registry.py 文件中查看 raise AppRegistryNotReady

def check_models_ready(self):
    """
    Raises an exception if all models haven‘t been imported yet.
    """
    if not self.models_ready:
        raise AppRegistryNotReady("Models aren‘t loaded yet.")

通过注释可以看出引起异常的原因是因为 models 没有被 import

于是在程序开头 import 处加入了

from deploy.models import *

再次运行报错依旧.

在官网文档中搜索 AppRegistryNotReady 异常时发现关于 Standalone scripts 的描述.

技术分享

简单来讲,Django 测试依赖于 DJANGO_SETTINGS_MODULE 环境变量. 如果我们想要使用单独的 PY 脚本来测试 Django,那么应该在我们的程序开始初始化 Django 环境.否则就会报出 AppRegistryNotReady 异常.

# 初始化命令
import django
django.setup()

增加之后运行正常.

随即查看了 django.setup() 源码.

from django.utils.version import get_version

VERSION = (1, 8, 0, ‘alpha‘, 0)

__version__ = get_version(VERSION)


def setup():
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    """
    from django.apps import apps
    from django.conf import settings
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    apps.populate(settings.INSTALLED_APPS)

关于 django.setup() 方法的官方描述

 

技术分享

 

参考文档

  ■  https://docs.djangoproject.com/en/1.8/releases/1.7/#app-loading-changes

  ■  https://docs.djangoproject.com/en/1.8/ref/applications/#django.setup

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。