How do I get the object if it exists, or None if it does not exist in Django? How do I get the object if it exists, or None if it does not exist in Django? python python

How do I get the object if it exists, or None if it does not exist in Django?


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:    go = SomeModel.objects.get(foo='bar')except SomeModel.DoesNotExist:    go = None

What I did do, is to subclass 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').


Since django 1.6 you can use first() method like so:

Content.objects.filter(name="baby").first()


From django docs

get() raises a DoesNotExist exception if an object is not 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 ObjectDoesNotExisttry:    go  = Content.objects.get(name="baby")except ObjectDoesNotExist:    go = None


matomo