how to catch the MultipleObjectsReturned error in django


Is it possible to catch the MultipleObjectsReturned error in Django?

I do a searchquery and if there are more than one objects I want that the first in the list will be taken so I tried this:

except MultipleObjectsReturned:

However, it exists in the doc though

global variable MultipleObjectsReturned does not exist


This isn’t the best practice. You can technically do this without using exceptions. Did you intend to use Location and Car in this example?

You can do this:


I strongly suggest you read the Django QuerySet API reference.

To answer your question about where the exception exists — you can always access these QuerySet exceptions on the model itself. E.g. Location.DoesNotExist and Location.MultipleObjectsReturned. You don’t need to import them if you already have the model imported.

Answered By – veggie1

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published