It seems like there are some deeper issues with your code, but without more information those are difficult to debug. As far as your original question however, your line:
except MultipleObjectsReturned, e:
Will only catch exceptions of the type MultipleObjectsReturned
. If you look at your traceback however, you see the actual exception being raised is a DoesNotExist
exception.
If you change your except line (above) to :
except DoesNotExist, e:
It should properly catch that exception.
As for why the exception is raised in the first place, I'm willing to guess that you just don't have that object in your database. Are you inserting it anywhere? If you're looking for a backend that will automatically construct an entry for you when you try to access it, look into mongodb
. Your current SQL
database however, will error if you try to access an object that does not exist.
Based on what you said in the comments, it seems you misunderstand exactly what exception handling is. Specifically when you catch
an exception, you are saying "This is an error that I am aware may happen and I have a contingency case for it".
The reason you might get a MultipleObjectsReturned
exception is because the get
method you used above is specifically for returning a single result. If you want to query for multiple entries you use a filter
instead:
my_objects = RealEstateAgent.objects.filter(name='bh')
which will return a QuerySet
filled with entries that match your query.
With that said, since a DoesNotExist
exception is being raised, your assumption that there are five objects matching the query in your database appears to be incorrect.
To address your use case, you could pretty easily implement something along these lines:
my_objects = RealEstateAgent.objects.filter(name='bh')
if len(my_objects) > 1:
# Ask user to pick one