Getting first row from sqlalchemy

孤街醉人 提交于 2019-11-27 11:26:51

问题


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


回答1:


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.




回答2:


You can use the first() function on the Query object. This will return the first result, or None if there are no results.

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.

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'



回答3:


Use one_or_none(). Return at most one result or raise an exception.

Returns None if the query selects no rows.




回答4:


Assuming you have a model User, you can get the first result with:

User.query.first()

If the table is empty, it will return None.



来源:https://stackoverflow.com/questions/18110033/getting-first-row-from-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!