Getting first row from sqlalchemy

0 votes
For the following example :

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?
Feb 21, 2019 in Python by ana1504.k
• 7,910 points
5,404 views

1 answer to this question.

0 votes
Use  query.one() to get one result. In all other cases it will raise an exception you can handle. Try the following :

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
answered Feb 21, 2019 by SDeb
• 13,300 points

Related Questions In Python

0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
2,013 views
0 votes
1 answer

Start an iteration on first row of a group Pandas

For anyone needing this information in the ...READ MORE

answered Sep 6, 2018 in Python by Priyaj
• 58,090 points
2,065 views
0 votes
1 answer

How can I convert a list of dictionaries from a CSV into a JSON object in Python?

You could try using the AST module. ...READ MORE

answered Apr 17, 2018 in Python by anonymous
3,215 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,007 views
0 votes
1 answer
0 votes
1 answer

How to exit from Python without traceback?

You are presumably encountering an exception and ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 13,300 points
865 views
0 votes
1 answer

Get path from open file in Python

The key here is the name attribute ...READ MORE

answered Jan 16, 2019 in Python by SDeb
• 13,300 points
1,145 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP