Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

However, it exists in the doc though

global variable MultipleObjectsReturned does not exist

like image 320
Tom Avatar asked Aug 24 '15 00:08

Tom


People also ask

How does Django handle connection error?

You stated that you are running the server on Ubuntu while you are trying to connect it from another PC running Windows. In that case, you should replace the 127.0. 0.1 with the actual IP address of Ubuntu server (the one you use for PuTTY). Show activity on this post.

What is attribute error in Django?

These errors yield to the program not being executed. One of the error in Python mostly occurs is “AttributeError”. AttributeError can be defined as an error that is raised when an attribute reference or assignment fails. For example, if we take a variable x we are assigned a value of 10.


1 Answers

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() 
like image 144
rofls Avatar answered Sep 21 '22 02:09

rofls