John Bachir
John Bachir

Reputation: 22711

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?

Upvotes: 7

Views: 13636

Answers (4)

dkhamrick
dkhamrick

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

Ben
Ben

Reputation: 5198

SQLAlchemy core provides a .limit(1) operator on a query.

Upvotes: 1

van
van

Reputation: 76962

First of all, agree and support other answers.

However, it looks like that your queries are for the primary key column. If this is the case, the most straightforward way of making such a query would be to simply call get():

thing = Thing.query.get(thing_id)

Upvotes: 4

jwodder
jwodder

Reputation: 57470

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

Upvotes: 15

Related Questions