Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I invoke an SQLAlchemy query with limit of 1?

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?

like image 800
John Bachir Avatar asked May 10 '16 18:05

John Bachir


1 Answers

There's first():

first() applies a limit of one and returns the first result as a scalar

Thus:

thing = thing.query.filter_by(id=thing_id).first()
like image 157
jwodder Avatar answered Sep 20 '22 16:09

jwodder