在 Django 1.8 或更高版本中填充时出现“模型尚未加载”错误

Posted

技术标签:

【中文标题】在 Django 1.8 或更高版本中填充时出现“模型尚未加载”错误【英文标题】:"Models aren't loaded yet" error while populating in Django 1.8 or later 【发布时间】:2014-10-04 08:40:26 【问题描述】:

我正在使用此代码来填充我的数据库:

import os
def populate():
    python_cat = add_cat('Python')

    add_page(cat=python_cat, 
    title="Official Python Tutorial",
    url="http://docs.python.org/2/tutorial/")

    add_page(cat=python_cat,
    title="How to Think like a Computer Scientist",
    url="http://www.greenteapress.com/thinkpython/")

    add_page(cat=python_cat,
    title="Learn Python in 10 minutes",
    url="http://www.korokithakis.net/tutorials/python/")

    django_cat = add_cat(name="Django")

    add_page(cat=django_cat,
    title="Official Django Tutorial",
    url="http://djangoproject.com/en/1.5/intro/tutorial01/")

    add_page(cat=django_cat,
    title="Django Rocks",
    url="http://www.djangorocks.com/")

    add_page(cat=django_cat,
    title="How to Tango with Django",
    url="htttp://www.tangowithdjango.com/")

    frame_cat = add_cat(name="Other Frameworks")

    add_page(cat=frame_cat, 
    title="Bottle",
    url="http://bottlepy.org/docs/dev/")

    add_page(cat=frame_cat, 
    title="Flask",
    url="http://flask.pocoo.org")

    # Print out what we have added to the user. 
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print "- 0 - 1".format(str(c), str(p))

def add_page(cat, title, url, views=0):
    p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]
    return p

def add_cat(name):
    c = Category.objects.get_or_create(name=name)
    return c

if __name__ == '__main__':
    print "Starting Rango population script..."
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'p.settings')
    from rango.models import Category, Page
    populate()

正在运行

python c:\python27\p\populate_rango.py

它给出了错误:

Staring Rango population script...
Traceback (most recent call last):
File "c:\python27\p\populate_rango.py", line 59, in <module>
populate()
File "c:\python27\p\populate_rango.py", line 4, in populate
python_cat = add_cat('Python')
File "c:\python27\p\populate_rango.py", line 52, in add_cat
c = Category.objects.get_or_create(name=name)
File "C:\Python27\Lib\site-packages\django\db\models\manager.py", li
manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\Lib\site-packages\django\db\models\query.py", line
et_or_create
return self.get(**lookup), False
File "C:\Python27\Lib\site-packages\django\db\models\query.py", line
clone = self.filter(*args, **kwargs)
File "C:\Python27\Lib\site-packages\django\db\models\query.py", line
ilter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\Lib\site-packages\django\db\models\query.py", line
filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\Lib\site-packages\django\db\models\sql\query.py",
in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "C:\Python27\Lib\site-packages\django\db\models\sql\query.py",
in _add_q
current_negated=current_negated, connector=connector)
File "C:\Python27\Lib\site-packages\django\db\models\sql\query.py",
in build_filter
lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
File "C:\Python27\Lib\site-packages\django\db\models\sql\query.py",
in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, se
a())
File "C:\Python27\Lib\site-packages\django\db\models\sql\query.py",
in names_to_path
field, model, direct, m2m = opts.get_field_by_name(name)
File "C:\Python27\Lib\site-packages\django\db\models\options.py", li
get_field_by_name
cache = self.init_name_map()
File "C:\Python27\Lib\site-packages\django\db\models\options.py", li
init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "C:\Python27\Lib\site-packages\django\db\models\options.py", li
get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "C:\Python27\Lib\site-packages\django\db\models\options.py", li
_fill_related_many_to_many_cache
for klass in self.apps.get_models():
File "C:\Python27\Lib\site-packages\django\utils\lru_cache.py", line
rapper
result = user_function(*args, **kwds)
File "C:\Python27\Lib\site-packages\django\apps\registry.py", line 1
_models
*self.check_models_ready()
File "C:\Python27\Lib\site-packages\django\apps\registry.py", line 1
ck_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.*

我的其余文件都可以,但出现此错误。我正在遵循 Tango with Django 书中的教程,但由于这本书指的是 Django 1.5.4,而我使用的是 Django 1.8,所以任何人都可以在这里帮助我吗?

【问题讨论】:

没有理由使用“Django 1.8”。 1.7还没有出来。您应该使用稳定版 1.6 或可能 1.7 候选版本。 我在 Django 1.7 final 中遇到了这个问题。接受的答案修复了它。 【参考方案1】:

我对 Django 1.7rc2 也有同样的例外。解决方案是在我的程序开头添加这些行:

import django
django.setup()

更新:This is now documented for Django 1.8.

【讨论】:

如果你在 Django 执行 python manage.py 后遇到这个错误,试试这个:***.com/q/25537905/540717 即使另一个模型已经在该包中工作,但后来我导入另一个模型突然发生加载尚未。你的答案解决了..谢谢.. 对于unittest 和run.py 脚本也非常有用! (可能在设置 PYTHONPATH 之后。) 在设置 DJANGO_SETTINGS_MODULE 的环境变量后添加。否则会产生配置不正确的错误。 docs.djangoproject.com/en/1.8/topics/settings/…docs.djangoproject.com/en/1.8/topics/settings/…的 setup() 的 Django 文档【参考方案2】:

我们遇到了这个错误。我们的项目从 Django 1.4 开始,我们到 1.5,然后到 1.7。我们的 wsgi.py 看起来像这样:

import os
import sys

from django.core.handlers.wsgi import WSGIHandler

os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = WSGIHandler()

当我更新到 1.7 样式的 WSGI 处理程序时:

import os
import sys

from django.core.wsgi import get_wsgi_application

os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = get_wsgi_application()

现在一切正常。

【讨论】:

当我升级到 django 1.8 时为我工作。谢谢+1【参考方案3】:

非常适合 django 1.9.x:

populate_rango.py:

import os
import sys

from django.core.wsgi import get_wsgi_application

os.environ['DJANGO_SETTINGS_MODULE'] = 'tango_with_django_project.settings'
application = get_wsgi_application()

def populate():
    python_cat = add_cat('Python')

    add_page(cat=python_cat,
         title="Official Python Tutorial",
         url="http://docs.python.org/2/tutorial/")

    add_page(cat=python_cat,
        title="How to Think like a Computer Scientist",
        url="http://www.greenteapress.com/thinkpython/")

    add_page(cat=python_cat,
        title="Learn Python in 10 Minutes",
        url="http://www.korokithakis.net/tutorials/python/")

    django_cat = add_cat("Django")

    add_page(cat=django_cat,
        title="Official Django Tutorial",
        url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")

    add_page(cat=django_cat,
        title="Django Rocks",
        url="http://www.djangorocks.com/")

    add_page(cat=django_cat,
        title="How to Tango with Django",
        url="http://www.tangowithdjango.com/")

    frame_cat = add_cat("Other Frameworks")

    add_page(cat=frame_cat,
        title="Bottle",
        url="http://bottlepy.org/docs/dev/")

    add_page(cat=frame_cat,
        title="Flask",
        url="http://flask.pocoo.org")

    #Print out what we have added to the user.
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print ("- 0 - 1".format(str(c), str(p)))

def add_page(cat, title, url, views=0):
    p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]
    return p

def add_cat(name):
    c = Category.objects.get_or_create(name=name)[0]
    return c

# Start execution here!
if __name__ == '__main__':
    print ("Starting Rango population script...")
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
    from rango.models import Category, Page
    populate()

【讨论】:

以上是关于在 Django 1.8 或更高版本中填充时出现“模型尚未加载”错误的主要内容,如果未能解决你的问题,请参考以下文章

django 找不到新的 sqlite 版本? (需要 SQLite 3.8.3 或更高版本(找到 3.7.17))

Android N 要求 IDE 运行 Java 1.8 或更高版本?

异步函数仅在面向 ECMAScript 2015 或更高版本时可用

不再支持源选项 5。使用 6 或更高版本的 Android Studio

如何在 api 17 或更高版本中使 android seekbar 全宽?

Android 8或更高版本使用Firebase Performance SDK在Android Oreo上崩溃的应用程序