Django使用外部文件对models操作容易产生的问题

from pv_server.models import IVCurvesInfo, FaultType
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PV_Moniter.settings')
django.setup()

def add_fault_type(fault_list, true_data_list, fault_decription_list=None):
    for item in fault_list:
        idx = fault_list.index(item)
        true_data =  true_data_list[idx]
        fault_decription = fault_decription_list[idx] if (fault_decription_list and fault_decription_list[idx]) \
            else None

        FaultType.addFault.create_faultType(item, true_data,fault_decription)

if __name__ == '__main__':
    add_fault_type(['normal', 'partial shadow_1', 'partial shadow_2',
                    'partial shadow_3', 'short circuit_1', 'short circuit_2',
                    'degradation_1', 'degradation_2', 'open_circuit'],
                   [0] * 9)
    print("Done!")

以上述代码为例

会产生

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.

的问题,这里要注意 明明已经增加了

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PV_Moniter.settings')
django.setup()

但,还是报错的原因是因为!!!!在导入models的时候,还没有在django对应的环境下导入

这里导入的顺序很重要

import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PV_Moniter.settings')
django.setup()

from pv_server.models import IVCurvesInfo, FaultType

这样更换导入顺序后,就顺利的解决啦!

猜你喜欢

转载自blog.csdn.net/qq_24724109/article/details/85855954