python - 检查 .one() 是否为空 sqlAlchemy

标签 python 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 上找到了解决方案(之前没找到) Getting first row from sqlalchemy

最佳答案

使用 first() 函数代替 one()。如果没有结果,它将返回 None。

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

参见文档 here

关于python - 检查 .one() 是否为空 sqlAlchemy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24985989/

相关文章:

python - Flask SqlAlchemy 有没有办法将表格大小限制为 n 行

python - 在 Python 中复制矩阵

python - 使用 SqlAlchemy 在 __init__ 上一致应用东西

python - 在 Pyramid 框架中使用 Mysql 和 SqlAlchemy

python - haproxy 背后扭曲的应用程序

python - SQLAlchemy 插入数据与关联表的多对多关系

python - SqlAlchemy 超前缓存?

python - 如何在 NetworkX 中仅绘制前 50-100 个连通分量子图;一次绘制多个子图

python - openpyxl - x 和 y 轴刻度的增量

python - 如何在 pandas 的 DataFrame.plot.hist 中使用不同的轴刻度?