Getting first row from sqlalchemy Getting first row from sqlalchemy flask flask

Getting first row from sqlalchemy


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 NoResultFoundfrom sqlalchemy.orm.exc import MultipleResultsFoundtry:    user = session.query(User).one()except MultipleResultsFound, e:    print e    # Deal with itexcept 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.


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, MultipleResultsFoundtry:    result = session.query(profile.name).filter(...).one()    print resultexcept NoResultFound:    print 'No result was found'except MultipleResultsFound:    print 'Multiple results were found'


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.