zoukankan      html  css  js  c++  java
  • 在python文件中操作django orm提示环境变量设置问题

    今天在通过python文件中单独操作并运行django orm操作的时候,运行.py文件时遇到以下的问题:

    Traceback (most recent call last):
    ...
        self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
      File "D:ProgramPython37libsite-packagesdjangoconf\__init__.py", line 56, in __getattr__
        self._setup(name)
      File "D:ProgramPython37libsite-packagesdjangoconf\__init__.py", line 39, in _setup
        % (desc, ENVIRONMENT_VARIABLE))
    django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
    

    查看.py文件的代码如下,简单的几行,看起来也没什么问题:

    import os
    import django
    from orm_practice import models
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BookManage.settings")
    django.setup()
    
    ret = models.Person.objects.all()
    print(ret)
    

    经过对比老师课上写的代码,发现from orm_practice import models 这一行不能放在环境变量设置之前,按以下修改的代码就可以正常运行:

    import os
    import django
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BookManage.settings")
    django.setup()
    
    from orm_practice import models
    ret = models.Person.objects.all()
    print(ret)
    

    再运行的话就不再报错了。

    <QuerySet []>
    
    Process finished with exit code 0
    
  • 相关阅读:
    Codeforces 120F Spiders
    Codeforces 509C Sums of Digits
    Topcoder SRM 497 DIV2 1000 MakeSquare
    codeforces 22B Bargaining Table
    Codeforces 487B Strip
    Codeforces 132C Logo Turtle
    关闭窗口对话框提示 messagedlg应用和showmodal的使用
    如何让窗口显示在电脑屏幕中间
    delphi项目程序输出编译成应用程序文件
    delphi程序项目创建和保存
  • 原文地址:https://www.cnblogs.com/xiaodou-cao/p/12510460.html
Copyright © 2011-2022 走看看