简体   繁体   English

为什么在try块中获得MultipleObjectsReturned错误?

[英]Why am getting a MultipleObjectsReturned error inside a try block?

Any help on this one would great. 对这一个的任何帮助都会很棒。 I'm using python 2.7 and django 1.2 Here's my code: 我正在使用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

I get a MultipleObjectsReturned error everytime when it hits the get() statement. 每次遇到get()语句时,我都会收到MultipleObjectsReturned错误。 I'm no expert at python so I imagine I missed something simple. 我不是python的专家所以我想我错过了一些简单的东西。

Two objects have the name values equal to the value of save 两个对象的name值等于save的值

When using get and there are more than 1 row returned it raises MultipleObjectsReturned 当使用get并且返回的行超过1行时,它会引发MultipleObjectsReturned

I think you should catch this explicitly because your except as it stands will also catch DoesNotExist errors (and all oteher errors) 我认为你应该明确地抓住这个,因为你的DoesNotExist除了它还会捕获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

Because you have more than 1 record in the database with name=save. 因为您在数据库中有多个记录,其中name = save。 Use filter() and get the one at index 0 if you want just one or properly handle that case separately . 使用filter()并获取索引为0的那个,如果你只需要一个或分别正确处理该情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Try 块 WebDriverWait 中出现错误 - Python Selenium - Getting error inside Try block WebDriverWait - Python Selenium 为什么我从 try 条件中得到错误? - why I am getting error from the try condition? 为什么会出现“ _csv.Error:字符串中的换行符”? - Why am I getting “_csv.Error: newline inside string”? 如何在具有多个对象的表单中使用初始值而不会出现 MultipleObjectsReturned 错误 - How to use initial in a form with multiple objects without getting MultipleObjectsReturned Error 为什么在“try”块之后的行中有语法错误? - Why is there a syntax error in the line following a "try" block? 为什么我会得到“预期一个缩进块”? - Why am I getting `expected an indented block`? 当我在try块中已定义str1时,运行此代码时出现错误,提示未定义str1 - I am getting an error when running this code saying str1 is not defined,when i have already defined it in try block 为什么每次尝试运行 VS Code python 终端时都会出现语法错误? - Why am I getting a syntax error whenever I try to run VS code python terminal? 当我尝试回答我自己的 dns 请求时,为什么会出现此错误? - Why am i getting this error when i try to answer my own dns request? 当我尝试运行Pyramid项目时,为什么会出现DistributionNotFound错误? - Why am I getting DistributionNotFound error when I try to run Pyramid project?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM