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
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.
解决方案
-
90% 成功率
Use .scalar_one() if you expect exactly one row, or .one_or_none() if zero is acceptable.
-
95% 成功率
Add filters to narrow down the result: query.filter(User.id == some_id).one()
无效尝试
常见但无效的做法:
-
60% 失败
Silently ignores extra rows, possibly hiding data issues.
-
70% 失败
Doesn't solve the root cause; may still return the wrong row.