Why are you getting the MultipleObjectsReturned error inside the try block?

Any help on this would be great. I am 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 an error MultipleObjectsReturned

every time it hits the statement get()

. I am not an expert in python, so I guess I am missing something simple.

+3


source to share


2 answers


Two objects have values name

equal to valuesave

When used get

and more than 1 line is returned, it raisesMultipleObjectsReturned



I think you should catch this explicitly because yours, apart from being worth it, will also catch errors DoesNotExist

(and all other 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

      

+9


source


Since there is more than one record in the database named = save. Use filter () and get the value at index 0 if you only want one, or properly handle this case separately.



+3


source







All Articles