簡體   English   中英

檢查 .one() 是否為空 sqlAlchemy

[英]check if .one() is empty sqlAlchemy

我正在運行基於查詢的其他 id 的查詢。 我的問題是有時查詢找不到結果。 我如何檢查結果是否為 None,而不是讓整個程序崩潰?

這是我的查詢:

sub_report_id = DBSession.query(TSubReport.ixSubReport).filter(and_(TSubReport.ixSection==sectionID[0], TSubReport.ixReport== reportID[0])).one()

當代碼被執行並且沒有找到結果時,我得到一個 NoResultFound 異常

NoResultFound: No row was found for one()

如果沒有結果,有沒有辦法跳過查詢?

在 SO 上找到解決方案(之前找不到) 從 sqlalchemy 獲取第一行

使用first()函數而不是one() 如果沒有結果,它將返回 None 。

sub_report_id = DBSession.query(TSubReport.ixSubReport).filter(and_(TSubReport.ixSection==sectionID[0], TSubReport.ixReport== reportID[0])).first()

請參閱此處的文檔

您也可以使用one_or_none() ,當找不到結果時返回None並且在語法上比first()更清晰。 不需要錯誤處理。

參考: one_or_none()

如果不進行查詢,SQLAlchemy 如何知道不會有結果?

您應該捕獲異常並處理它然后:

from sqlalchemy.orm.exc import NoResultFound

try:
    sub_report_id = DBSession.query(TSubReport.ixSubReport).filter(and_(TSubReport.ixSection==sectionID[0], TSubReport.ixReport== reportID[0])).one()
except NoResultFound:
    sub_report_id = []  # or however you need to handle it

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM