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'