python data_error ai_generated true

sqlalchemy.exc.MultipleResultsFound: 当恰好需要一行时,找到了多行

sqlalchemy.exc.MultipleResultsFound: Multiple rows were found when exactly one was required

ID: python/sqlalchemy-query-multiple-rows

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-02-14首次发现

版本兼容性

版本状态引入弃用备注
1.4.x active
2.0.x active

根因分析

对返回多行的查询使用了 .one()。

English

Using .one() on a query that returns more than one row.

generic

解决方案

  1. 90% 成功率
    Use .scalar_one() if you expect exactly one row, or .one_or_none() if zero is acceptable.
  2. 95% 成功率
    Add filters to narrow down the result: query.filter(User.id == some_id).one()

无效尝试

常见但无效的做法:

  1. 60% 失败

    Silently ignores extra rows, possibly hiding data issues.

  2. 70% 失败

    Doesn't solve the root cause; may still return the wrong row.