在指令碼中單獨使用django的ORM模型詳解

2022-09-29 13:48:12 字數 2213 閱讀 6535

有時候在測試django中一些模組時,不想重新跑一整個django專案,只想跑單個檔案,正好寫在if __name__ == '__main__': 這樣也不會打擾到正常的**邏輯

方法正常方法

大家都知道的方法就是'python manage.py shell',當然我知道這可能不是你需要的;

更好用的方法

在指令碼中import模型前呼叫下面幾行即可:

import os, sys

base_dir = os.path.dirname(os.path.abspath(__file__)) # 定位到你的django根目錄

sys.path.append(os.path.abspath(os.path.join(base_dir, os.pardir)))

os.environ.setdefault("django_settings_module", "dj_tasks.settings") # 你的django的settings檔案

程式設計客棧接下來再呼叫'from ***x.models import ***'就不會報錯了

補充知識: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_faultwww.cppcns.com_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

這樣更換匯入順序後,就順利的解決啦!

本文標題: 在指令碼中單獨使用django的orm模型詳解

本文位址:

指令碼單獨呼叫django模組

需求場景 在寫django的時候,有時候會遇到我們需要使用django中的模型 model 但是指令碼 是單獨執行的,並不是和django服務一起執行的,這時候需要在檔案的開始部分做如下設定 import os,sys cmdb path os.path.dirname os.path.dirnam...

在django專案中,單獨執行python檔案

如果python檔案涉及到資料庫之類的 單獨執行python檔案會報錯 django.core.exceptions.improperlyconfigured requested setting media root,but settings are not configured.you must ...

Celery在Django中的使用

celery 是乙個強大的分布式任務佇列,它可以讓任務的執行完全脫離主程式,甚至可以被分配到其他主機上執行。我們通常使用它來實現非同步任務 async task 和定時任務 crontab 非同步任務 比如傳送郵件 手機驗證碼,或者檔案上傳,影象處理等等一些比較耗時的操作 定時任務 需要在特定時間執...