how to catch the MultipleObjectsReturned error in django how to catch the MultipleObjectsReturned error in django django django

how to catch the MultipleObjectsReturned error in django


Use a filter:

Location.objects.filter(name='Paul').first()

Or import the exception:

from django.core.exceptions import MultipleObjectsReturned...try:    Location.objects.get(name='Paul')except MultipleObjectsReturned:    Location.objects.filter(name='Paul').first()


This is more pythonic way to do it.

try:    Location.objects.get(name='Paul')except Location.MultipleObjectsReturned:    Location.objects.filter(name='Paul')[0]


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:

Location.objects.filter(name='Paul').order_by('id').first()

I strongly suggest you read the Django QuerySet API reference.

https://docs.djangoproject.com/en/1.8/ref/models/querysets/

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.