Reputation: 22711
I have code like this:
thing = thing.query.filter_by(id=thing_id).limit(1).all()[0]
all()[0]
feels a bit messy and redundant in the limit(1)
case. Is there a more terse (and/or otherwise optimal) way to achieve this?
Upvotes: 7
Views: 13636
Reputation: 402
Jwodder's answer will, indeed, return the first result as a scalar, but SQLAlchemy provides a couple other functions that may better suit your needs, so I have listed and explained all of them:
first()
applies a limit of one and returns the first result as a scalar, or None
if no row is returned. first()
one()
fully fetches all rows, and if not exactly one object identity or composite row is present in the result, raises an error. one()
one_or_none()
will essentially do a one()
, but instead of erroring out will return None
if no rows are returned. This will still error out if more than one rows is returned.
The documentation for all of these can be found here: http://docs.sqlalchemy.org/en/latest/orm/query.html
Upvotes: 10