Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is the difference between one and first methods in SQLAlchemy

like image 506
Reena Shirale Avatar asked Mar 20 '15 07:03

Reena Shirale


People also ask

What does First () do in Python?

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.

What does one_ or_ None return?

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.

How do I select in Sqlalchemy?

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.


1 Answers

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] 
like image 88
Martijn Pieters Avatar answered Sep 25 '22 08:09

Martijn Pieters