在 PyCharm 中,我创建了一个空白的新 Django 应用程序。创建了一些模型并发布manage.py makemigrations
and manage.py migrate
,我尝试编写一个独立的脚本,用初始数据填充数据库。在其导入中我写道:
from MyApp.models import Model1, Model2, …
遗憾的是,在 PyCharm 中运行此脚本会引发异常:django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
我用谷歌搜索了这个异常,并在 SO 中找到了答案https://stackoverflow.com/a/27455703/4385532 https://stackoverflow.com/a/27455703/4385532建议将其放在我的脚本的顶部:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
所以我做了。遗憾的是,这并没有解决问题。现在我遇到了另一个例外:django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
我应该怎么办?
确保您还执行以下操作:
import django
django.setup()
加载您的模型。
文档:https://docs.djangoproject.com/en/1.10/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage https://docs.djangoproject.com/en/1.10/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)