How to catch MultipleObjectsReturned error in django

Is it possible to catch the MultipleObjectsReturned error in Django?

I am doing a search query, and if there are several objects, I want the first in the list to be accepted, so I tried this:

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

However, it exists in the doc , although

global variable MultipleObjectsReturned does not exist

+5
source share
3 answers

This is not 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 it:

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

I highly recommend you read the Django QuerySet API link.

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 in the model itself. For instance. Location.DoesNotExist and Location.MultipleObjectsReturned . You do not need to import them if you have already imported the model.

+5
source

Use 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() 
+15
source

This is a more pythonic way of doing this.

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

All Articles