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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:33:36  来源:igfitidea点击:

check if .one() is empty sqlAlchemy

pythonsqlalchemypyramid

提问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

Use first()function instead of one(). It will return None if there is no results.

使用first()函数而不是one(). 如果没有结果,它将返回 None 。

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

see documentation here

请参阅此处的文档

回答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 Nonewhen there's no result found and is syntactically clearer than first(). No error handling required.

您也可以使用one_or_none(),这会None在找不到结果时返回,并且在语法上比first(). 不需要错误处理。

ref: one_or_none()

参考:one_or_none()