views:

67

answers:

2
go  = Content.objects.get(name="baby")
# go should be None, since nothing is in the database.
+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
+1 for catching the specific exception.
Jason Webb
+3  A: 

From django docs

get() raises a DoesNotExist exception if an object wasn't found for the given parameters. This exception is also an attribute of the model class. The DoesNotExist exception inherits from django.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