What is the difference between one
and first
methods in SQLAlchemy
The first() method returns the first n rows, based on the specified value. The index have to be dates for this method to work as expected.
one_or_none() , which will return None if there is no product named apple in your database, or an instance of class Product if there is exactly one product named apple in your database, or raises an exception if there are multiple products named apple in your database.
The select() method of table object enables us to construct SELECT expression. The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method. Here, we have to note that select object can also be obtained by select() function in sqlalchemy.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With