Getting first row from sqlalchemy

Asken picture Asken · Aug 7, 2013 · Viewed 78.9k times · Source

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

Answer

Lukas Graf picture Lukas Graf · Aug 7, 2013

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.