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

Question:

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?

Asked By: John Bachir

||

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()
Answered By: jwodder

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

Answered By: dkhamrick

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)
Answered By: van

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

Answered By: Ben
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.