Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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. I'm no expert at python so I imagine I missed something simple.

like image 400
Jacob Harding Avatar asked Jul 09 '26 08:07

Jacob Harding


1 Answers

Two objects have the name values equal to the value of save

When using get and there are more than 1 row returned it raises MultipleObjectsReturned

I think you should catch this explicitly because your except as it stands will also catch DoesNotExist errors (and all oteher errors)

    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
like image 113
dm03514 Avatar answered Jul 11 '26 20:07

dm03514



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!