[英]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.