carambo carambo - 3 months ago 9
Python Question

What's the equivalent of peewee's DoesNotExist in SQLAlchemy?

I've been using peewee with SQLite for some time and now I'm switching to SQLAlchemy with Postgres and I can't find equivalent of DoesNotExist (see example)

try:
return models.User.get(models.User.id == userid)
except models.DoesNotExist:
return None


Do you know how to achieve the same with SQLAlchemy? I've checked stuff which I can import from sqlalchemy.ext but nothing seemed right.

Answer

The closest could be this one: - http://docs.sqlalchemy.org/en/latest/orm/exceptions.html#sqlalchemy.orm.exc.NoResultFound

Code Sample:

from sqlalchemy.orm.exc import NoResultFound

try:
    user = session.query(User).one()
except NoResultFound, e:
    print "No users found"