【发布时间】:2016-09-20 04:51:39
【问题描述】:
假设我有一个名为person的表,当我想知道id=1的记录是否存在时,我会尝试下面的代码
if Person.query.filter_by(id = 1).count() > 0:
do_something()
问题是,当id=1 没有记录时,flask-sqlalchemy 只会抛出OperationalError 而不是返回0。这是否意味着count 在OperationalError 被捕获时为0?换句话说,我应该按以下方式进行吗:
try:
if Person.query.filter_by(id = 1).count() > 0:
do_something_when_record_exists()
except OperationalError:
do_something_when_theres_no_record()
finally:
other_code()
对我来说,这似乎不是一种优雅的方式。那么有没有更好的方法来实现呢?
【问题讨论】:
标签: python flask sqlalchemy flask-sqlalchemy