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

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

问题描述

我有以下查询:

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

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

解决方案

使用 query.one() 来得到一个,而正是一个结果。在所有其他情况下,它会引发一个异常,你可以处理:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $从$ sq $'$' sqlalchemy.orm.exc import MultipleResultsFound

try:
user = session.query(User).one()
除了MultipleResultsFound,e:
print e
#处理它
除了NoResultFound,e:
print e
#处理这个以及

还有 query.first() ,这将给你可能很多的第一个结果,而不会引发这些异常。但是既然你想处理没有结果或比你想象的更多的情况, query.one() 正是您应该使用的。


I have the following query:

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)?

解决方案

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

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天全站免登陆