go = Content.objects.get(name="baby")
# go should be None, since nothing is in the database.
views:
67answers:
2
+7
A:
There is no 'built in' way to do this. Django will raise the DoesNotExist exception every time. The idiomatic way to handle this in python is to wrap it in a try catch:
try:
x = SomeModel.objects.get(foo='bar')
except SomeModel.DoesNotExist:
x = None
What I did do, is to sublcass models.Manager, create a safe_get
like the code above and use that manager for my models. That way you can write: SomeModel.objects.safe_get(foo='bar')
Arthur Debert
2010-06-22 04:47:09
+1 for catching the specific exception.
Jason Webb
2010-06-22 05:41:41
+3
A:
get()
raises aDoesNotExist
exception if an object wasn't found for the given parameters. This exception is also an attribute of the model class. TheDoesNotExist
exception inherits fromdjango.core.exceptions.ObjectDoesNotExist
You can catch the exception and assign None
to go.
from django.core.exceptions import ObjectDoesNotExist
try:
go = Content.objects.get(name="baby")
except ObjectDoesNotExist:
go = None;
Amarghosh
2010-06-22 04:48:16