从 sqlalchemy 获取第一行 [英] Getting first row from sqlalchemy

查看:39
本文介绍了从 sqlalchemy 获取第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询:

profiles = session.query(profile.name).filter(and_(profile.email == email, profile.password == password_hash))

我如何检查是否有一行以及我如何只返回第一个(如果匹配,应该只返回一个)?

How do I check if there is a row and how do I just return the first (should only be one if there is a match)?

推荐答案

使用 query.one() 得到一个,恰好一个结果.在所有其他情况下,它会引发您可以处理的异常:

Use query.one() to get one, and exactly one result. In all other cases it will raise an exception you can handle:

from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.exc import MultipleResultsFound

try:
    user = session.query(User).one()
except MultipleResultsFound, e:
    print e
    # Deal with it
except NoResultFound, e:
    print e
    # Deal with that as well

还有 query.first(),它只会给你可能很多的第一个结果,而不会引发这些异常.但是由于您想处理没有结果或超出您预期的情况,query.one() 正是您应该使用的.

There's also query.first(), which will give you just the first result of possibly many, without raising those exceptions. But since you want to deal with the case of there being no result or more than you thought, query.one() is exactly what you should use.

这篇关于从 sqlalchemy 获取第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆