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

9👍

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

3👍

Because you have more than 1 record in the database with name=save. Use filter() and get the one at index 0 if you want just one or properly handle that case separately .

👤ustun

Leave a comment