python
data_error
ai_generated
true
django.core.exceptions.MultipleObjectsReturned: get() returned more than one Article -- it returned 2!
ID: python/django-orm-multiple-objects-returned
80%Fix Rate
88%Confidence
0Evidence
2024-01-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
使用get()查询时条件不唯一,匹配到多条记录
generic中文
ORM查询中get()方法要求唯一结果,但查询条件匹配了多条记录
Workarounds
-
95% success
article = Article.objects.filter(title='x').first()
-
80% success
添加unique=True约束或使用get_object_or_404
Dead Ends
Common approaches that don't work:
-
90% fail
order_by只影响排序,不影响返回数量,get()仍会抛出异常
-
60% fail
异常被吞掉后程序继续运行,可能导致数据不一致