check if .one() is empty sqlAlchemy

Question:

I am running a query based off of other ids for the query. The problem i have is that sometimes the query won’t find a result. Instead of having the entire program crash, how can I check to see if the result will be None?

This is the query I have:

sub_report_id = DBSession.query(TSubReport.ixSubReport).filter(and_(TSubReport.ixSection==sectionID[0], TSubReport.ixReport== reportID[0])).one()

When the code gets executed and no results are found, I get a NoResultFound exception

NoResultFound: No row was found for one()

is there a way to just skip the query if there is not going to be a result?

Found the solution on SO(couldn’t find it before)
Getting first row from sqlalchemy

Asked By: john

||

Answers:

How would SQLAlchemy know there wasn’t going to be a result without doing the query?

You should catch the exception and handle it then:

from sqlalchemy.orm.exc import NoResultFound

try:
    sub_report_id = DBSession.query(TSubReport.ixSubReport).filter(and_(TSubReport.ixSection==sectionID[0], TSubReport.ixReport== reportID[0])).one()
except NoResultFound:
    sub_report_id = []  # or however you need to handle it
Answered By: kylieCatt

Use first() function instead of one(). It will return None if there is no results.

sub_report_id = DBSession.query(TSubReport.ixSubReport).filter(and_(TSubReport.ixSection==sectionID[0], TSubReport.ixReport== reportID[0])).first()

see documentation here

Answered By: Lynch

You can also use one_or_none(), this returns None when there’s no result found and is syntactically clearer than first(). No error handling required.

ref: one_or_none()

Answered By: ythdelmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.