Python 从 sqlalchemy 获取第一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18110033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting first row from sqlalchemy
提问by Asken
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)?
我如何检查是否有一行以及我如何只返回第一个(如果有匹配,应该只有一个)?
采纳答案by Lukas Graf
Use query.one()
to get one, and exactlyone result. In all other cases it will raise an exception you can handle:
使用 query.one()
得到之一,正是一个结果。在所有其他情况下,它将引发您可以处理的异常:
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.
还有query.first()
,它只会给你可能很多的第一个结果,而不会引发这些异常。但既然你要处理没有结果或比你想象的更多的情况,这query.one()
正是你应该使用的。
回答by Mark Hildreth
You can use the first()
function on the Query object. This will return the first result, or None if there are no results.
您可以first()
在 Query 对象上使用该函数。这将返回第一个结果,如果没有结果,则返回 None。
result = session.query(profile.name).filter(...).first()
if not result:
print 'No result found'
Alternatively you can use one()
, which will give you the only item, but raise exceptions for a query with zero or multiple results.
或者,您可以使用one()
,它将为您提供唯一的项目,但会为具有零个或多个结果的查询引发异常。
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
try:
result = session.query(profile.name).filter(...).one()
print result
except NoResultFound:
print 'No result was found'
except MultipleResultsFound:
print 'Multiple results were found'
回答by Shoham
Use one_or_none(). Return at most one result or raise an exception.
使用one_or_none()。最多返回一个结果或引发异常。
Returns None if the query selects no rows.
如果查询未选择任何行,则返回 None。
回答by Aldo Canepa
Assuming you have a model User, you can get the first result with:
假设你有一个模型用户,你可以得到第一个结果:
User.query.first()
User.query.first()
If the table is empty, it will return None.
如果表为空,它将返回 None。