Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is the main difference between .one() and .scalar() in SQLAlchemy, as both doing the same jobs.

I saw some sites like tutorialpoint.com but that explanation is not enough for me to understand clearly

like image 222
Syed mohamed aladeen Avatar asked Apr 13 '19 07:04

Syed mohamed aladeen


2 Answers

SQLAlchemy has nice documentation.

one()

Return exactly one result or raise an exception.

Raises sqlalchemy.orm.exc.NoResultFound if the query selects no rows. Raises sqlalchemy.orm.exc.MultipleResultsFound if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities.

Link on one() method

scalar()

Return the first element of the first result or None if no rows present. If multiple rows are returned, raises MultipleResultsFound.

Link on scalar() method.

and if you will have some questions related to SQLAlchemy my recommendation - first of all, to check the documentation, since it's really powerful and clean.

like image 195
myusko Avatar answered Oct 22 '22 02:10

myusko


Here is the difference and when to use each:

When to use one():
If you have a query that should return 1 result, otherwise raise an exception – even if it returns 0 results. In other words, it does not allow empty results.

When to use scalar():
If you have a query that either returns 1 result or no results. Otherwise throw an exception. In other words, it does allow empty results.

like image 21
Brandon Thomas Avatar answered Oct 22 '22 03:10

Brandon Thomas