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
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.
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
.
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