check if .one() is empty sqlAlchemy

Solution 1:

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

Solution 2:

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()

Solution 3:

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