What is the difference between .one() and .first()

PythonSqlalchemyFlask Sqlalchemy

Python Problem Overview


What is the difference between one and first methods in SQLAlchemy

Python Solutions


Solution 1 - Python

Query.one() requires that there is only one result in the result set; it is an error if the database returns 0 or 2 or more results and an exception will be raised.

Query.first() returns the first of a potentially larger result set (adding LIMIT 1 to the query), or None if there were no results. No exception will be raised.

From the documentation for Query.one():

> Return exactly one result or raise an exception.

and from Query.first():

> Return the first result of this Query or None if the result doesn’t contain any row.

(emphasis mine).

In terms of a Python list, one() would be:

def one(lst):
    if not lst:
        raise NoResultFound
    if len(lst) > 1:
        raise MultipleResultsFound
    return lst[0]

while first() would be:

def first(lst):
    return lst[0] if lst else None

There is also a Query.one_or_none() method, which raises an exception only if there are multiple results for the query. Otherwise it'll return the single result, or None if there were no results.

In list terms, that'd be the equivalent of:

def one_or_none(lst):
    if not lst:
        return None
    if len(lst) > 1:
        raise MultipleResultsFound
    return lst[0]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionReena ShiraleView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow