PaolaJ.
PaolaJ.

Reputation: 11532

SQLAlchemy inner join NoneType is not iterable to avoid count()

I need to check if student has pass this exam with exam id ( table marks has foreign keys to students and table exams)

student, exam = session.query(StudentModel,MarkModel)
                       .join(MarkModel)
                       .filter(and_(StudentModel.uuid == uuid, MarkModel.exam_id == exam_id))
                       .first()

but when is not in database I get error NoneType is not iterable

How to check without fetching exception ? I wanted to avoid to execute two or more queries ( like to check first with count)

Upvotes: 0

Views: 1292

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

.first() returns one query result, or None. There were no matches, first() returned None and unpacking None fails.

You can check for None explicitly by first storing the result:

result = session.query(StudentModel,MarkModel).join(MarkModel).filter(
    and_(StudentModel.uuid == uuid, MarkModel.exam_id == exam_id)).first()
if result is not None:
    student, exam = result

Or just catch the exception:

try:
    student, exam = session.query(StudentModel,MarkModel).join(MarkModel).filter(
        and_(StudentModel.uuid == uuid, MarkModel.exam_id == exam_id)).first()
except TypeError:
    # None returned, unpacking failed
    student = exam = None

Upvotes: 2

Related Questions