Python 检查 .one() 是否为空 sqlAlchemy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24985989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check if .one() is empty sqlAlchemy
提问by john
I am running a query based off of other ids for the query. The problem i have is that sometimes the query won't find a result. Instead of having the entire program crash, how can I check to see if the result will be None?
我正在运行基于查询的其他 id 的查询。我的问题是有时查询找不到结果。我如何检查结果是否为 None,而不是让整个程序崩溃?
This is the query I have:
这是我的查询:
sub_report_id = DBSession.query(TSubReport.ixSubReport).filter(and_(TSubReport.ixSection==sectionID[0], TSubReport.ixReport== reportID[0])).one()
When the code gets executed and no results are found, I get a NoResultFound exception
当代码被执行并且没有找到结果时,我得到一个 NoResultFound 异常
NoResultFound: No row was found for one()
is there a way to just skip the query if there is not going to be a result?
如果没有结果,有没有办法跳过查询?
Found the solution on SO(couldn't find it before) Getting first row from sqlalchemy
在 SO 上找到解决方案(之前找不到) 从 sqlalchemy 获取第一行
采纳答案by Lynch
回答by kylie.a
How would SQLAlchemy know there wasn't going to be a result without doing the query?
如果不进行查询,SQLAlchemy 如何知道不会有结果?
You should catch the exception and handle it then:
您应该捕获异常并处理它然后:
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
回答by ythdelmar
You can also use one_or_none()
, this returns None
when there's no result found and is syntactically clearer than first()
. No error handling required.
您也可以使用one_or_none()
,这会None
在找不到结果时返回,并且在语法上比first()
. 不需要错误处理。
ref: one_or_none()