在查询的时候,经常需要先判断是否存在结果,再进行下一步操作。 这里总结了判断查询结果是否存在的几种方式
count()方法返回记录条数,使用示例
with app.app_context():
count = Students.query.filter(Students.name == 'yy').count()
if count > 0:
print('查询结果存在')
else:
print('查询结果不存')
当查询结果为0时,抛异常sqlalchemy.exc.NoResultFound
当查询结果为唯一时,返回该对象<Students(id='1', name='yy', fullname='yoyo')>
当查询结果为不止一个时,抛异常sqlalchemy.exc.MultipleResultsFound
with app.app_context():
res = Students.query.filter(Students.name == 'yy').one()
print(res)
# 查询结果唯一时,返回<Students(id='1', name='yy', fullname='yoyo')>
当查询结果为0时,返回None
当查询结果为唯一时,返回该对象<Students(id='1', name='yy', fullname='yoyo')>
当查询结果为不止一个时,抛异常sqlalchemy.exc.MultipleResultsFound
with app.app_context():
res = Students.query.filter(Students.name == 'yy').one()
print(res)
# 查询结果唯一时,返回<Students(id='1', name='yy', fullname='yoyo')>
功能同one_or_none() 一样
当查询结果为0时,返回None
当查询结果为唯一时,返回该对象<Students(id='1', name='yy', fullname='yoyo')>
当查询结果为不止一个时,抛异常sqlalchemy.exc.MultipleResultsFound
with app.app_context():
res = Students.query.filter(Students.name == 'yy').scalar()
print(res)
first() 会从查询结果中返回第一个值,如果没有结果返回None 如果有一个或多个结果返回第一个值,不会抛异常,所以用first()判断是否有结果也很方便
with app.app_context():
obj = Students.query.filter(Students.name == 'yy')
if obj.first():
print("查询到结果")
else:
print("未查询到结果")
all()方法返回全部数据,返回的是一个list
如果没查询到数据,返回空的list[]
查询到结果返回list of obj 格式[<Students(id='1', name='yy', fullname='yoyo')>]
with app.app_context():
obj = Students.query.filter(Students.name == 'yy')
print(obj.all())
# [<Students(id='1', name='yy', fullname='yoyo')>]
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有