[Python] Is session.scalar(stmt) equivalent to session.execute(stmt).scalar_one_or_none()...

Discussão em 'Python' iniciado por Stack, Junho 30, 2025.

  1. Stack

    Stack Membro Participativo

    This is my best guess by jumping around the docs, since it seems like both return a Scalar if any is found, and None if there isn't any found.

    I tried comparing these two functions, which seemed to follow that same behavior (returning None if not found, and a single scalar if it is found):

    def get_band1(session: Session, band_id: int) -> Band | None:
    stmt = select(Band).filter_by(id=band_id)
    return session.scalar(stmt)


    def get_band2(session: Session, band_id: int) -> Band | None:
    stmt = select(Band).filter_by(id=band_id)
    return session.execute(stmt).scalar_one_or_none()


    Just want to make sure I understand this correctly. Thanks!

    Continue reading...

Compartilhe esta Página