python - 为什么在 try block 中出现 MultipleObjectsReturned 错误?

标签 python django exception

在这方面的任何帮助都会很棒。我正在使用 python 2.7 和 django 1.2 这是我的代码:

for save in saved: #list to iterate
    try:
        sect = obj.get(name=save) #obj is a RelatedManager
    except: #if two sections have the same name
        sect = obj.filter(name=save)
    else:
        #finish my code

每次遇到 get() 语句时,我都会收到一个 MultipleObjectsReturned 错误。我不是 Python 专家,所以我想我错过了一些简单的事情。

最佳答案

两个对象的 name 值等于 save 的值

当使用 get 并且返回的行超过 1 行时,它会引发 MultipleObjectsReturned

我认为你应该明确地捕捉到这一点,因为你的 except 本身也会捕捉到 DoesNotExist 错误(以及所有其他错误)

    from django.core.exceptions import MultipleObjectsReturned

    try:
        sect = obj.get(name=save) #obj is a RelatedManager
    except MultipleObjectsReturned: #if two sections have the same name
        sect = obj.filter(name=save)[0]
    else:
        #finish my code

关于python - 为什么在 try block 中出现 MultipleObjectsReturned 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14526355/

相关文章:

python - 没有名为 numpy 的模块与 pypy

python - 检查 Django 查询集过滤中字段列表的 is_null

python - 重新加载 mod_wsgi 守护进程时停机?

python - Doc2vec : How to get document vectors

python - 使用 Python,以整数形式获取当前月份的日期

javascript - Jquery Load 是 django 模板中的重复行为

python - 在其消费者中处理生成器异常

Java 反射 API 包装器(该死的检查异常困惑)

exception - NotFoundException 的 HTTP 状态代码 500

python - Matplotlib 三角测量 : more triangles than vertices