【转载】django 对于外部文件调用model 对象

1.对于外部文件直接调用 model 对象的话,会直接报如下错误:

django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
 

 

 

 

2.此时对于该问题,分2种情况

①.在django项目中,需要在导入model前,需配置环境

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ZJTAutoTestingPlatform.settings")
配置环境后再导入model

from apitest.models import GloabVariable  #此类为 model 类

 

②.在非django项目启动中,配置环境启动,如图,报错:django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

 

此时需要额外启动,当然也是在导入model类前

import django
django.setup()

 

 

完整代码为:

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ZJTAutoTestingPlatform.settings")
import django

django.setup()
from apitest.models import GloabVariable

 

 

转载自:https://blog.csdn.net/qq_33733970/article/details/78912162

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章