python data_error ai_generated true

django.core.exceptions.MultipleObjectsReturned: get() returned more than one MyModel -- it returned 2!

ID: python/django-multiple-objects-returned

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-10-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.2 active
4.0 active
5.0 active

Root Cause

使用 get() 查询时,条件匹配了多个记录

generic

中文

get() 方法期望唯一结果,但查询条件返回了多条记录

Workarounds

  1. 95% success 使用 filter() 并获取第一个对象
    obj = MyModel.objects.filter(condition).first()
  2. 90% success 添加唯一约束
    在模型字段中添加 unique=True 或使用 unique_together

Dead Ends

Common approaches that don't work:

  1. 忽略错误继续执行 100% fail

    异常会导致程序中断,无法忽略

  2. 使用 filter() 代替 get() 50% fail

    filter() 返回 QuerySet,后续代码可能期望单个对象