Frage

RealEstateAgent is a model and doing RealEstateAgent.objects.filter(name = 'better homes') returns 5 objects.

I would like to use RealEstateAgent.objects.get(name='better homes') to catch the MultipleObjectsReturned exception.

Im trying this but the exception is not getting caught.

from django.core.exceptions import MultipleObjectsReturned
try:
  RealEstateAgent.objects.get(name='bh')
except MultipleObjectsReturned, e:
  print ''

this is the traceback:

DoesNotExist                              Traceback (most recent call last)
<ipython-input-49-9458986408df> in <module>()
      1 try:
----> 2     RealEstateAgent.objects.get(name='better homes')
      3 except MultipleObjectsReturned, e:
      4     print ''
      5 

/home/dubizzle/webapps/django/src/django/django/db/models/manager.pyc in get(self, *args, **kwargs)
    130 
    131     def get(self, *args, **kwargs):
--> 132         return self.get_query_set().get(*args, **kwargs)
    133 
    134     def get_or_create(self, **kwargs):

/home/dubizzle/webapps/django/src/django/django/db/models/query.pyc in get(self, *args, **kwargs)
    347         if not num:
    348             raise self.model.DoesNotExist("%s matching query does not exist."
--> 349                     % self.model._meta.object_name)
    350         raise self.model.MultipleObjectsReturned("get() returned more than one %s -- it returned %s! Lookup parameters were %s"
    351                 % (self.model._meta.object_name, num, kwargs))

DoesNotExist: RealEstateAgent matching query does not exist.
War es hilfreich?

Lösung

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top