python runtime_error ai_generated true

sqlalchemy.orm.exc.MultipleResultsFound: Multiple rows were found for one()

ID: python/sqlalchemy-orm-query-multiple-results

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2025-08-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Using .one() when query returns more than one row.

generic

中文

当查询返回多行时使用 .one()。

Workarounds

  1. 95% success Use .one_or_none() if row may not exist.
    user = session.query(User).filter_by(email='[email protected]').one_or_none()
  2. 90% success Add additional filter to ensure uniqueness.
    user = session.query(User).filter(User.id == 1).one()

Dead Ends

Common approaches that don't work:

  1. Using .first() without checking for uniqueness. 70% fail

    Returns first row but may miss intended unique row.

  2. Catching exception and returning None. 60% fail

    Hides potential data integrity issues.