Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first row from sqlalchemy

I have the following query:

profiles = session.query(profile.name).filter(and_(profile.email == email, profile.password == password_hash)) 

How do I check if there is a row and how do I just return the first (should only be one if there is a match)?

like image 869
Asken Avatar asked Aug 07 '13 17:08

Asken


People also ask

What is first () in SQLAlchemy?

first() , which will give you just the first result of possibly many, without raising those exceptions. But since you want to deal with the case of there being no result or more than you thought, query. one() is exactly what you should use.

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.

How do I get column values in SQLAlchemy?

Get value by column name The given task can be performed by first creating an engine with sqlalchemy, connecting with the database, and executing an SQL query with the connection. The SQL query will contain the name of the column/columns whose values we want and then we will get a result object.


2 Answers

You can use the first() function on the Query object. This will return the first result, or None if there are no results.

result = session.query(profile.name).filter(...).first()  if not result:     print 'No result found' 

Alternatively you can use one(), which will give you the only item, but raise exceptions for a query with zero or multiple results.

from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound try:     result = session.query(profile.name).filter(...).one()     print result except NoResultFound:     print 'No result was found' except MultipleResultsFound:     print 'Multiple results were found' 
like image 24
Mark Hildreth Avatar answered Sep 22 '22 00:09

Mark Hildreth


Use query.one() to get one, and exactly one result. In all other cases it will raise an exception you can handle:

from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import MultipleResultsFound  try:     user = session.query(User).one() except MultipleResultsFound, e:     print e     # Deal with it except NoResultFound, e:     print e     # Deal with that as well 

There's also query.first(), which will give you just the first result of possibly many, without raising those exceptions. But since you want to deal with the case of there being no result or more than you thought, query.one() is exactly what you should use.

like image 57
Lukas Graf Avatar answered Sep 20 '22 00:09

Lukas Graf