go = Content.objects.get(name="baby") # go should be None, since nothing is in the database.
There's no 'built in' method of doing this. Django will heighten the DoesNotExist exception each time. The idiomatic way additional in python would be to wrap it inside a try catch:
try: x = SomeModel.objects.get(foo='bar') except SomeModel.DoesNotExist: x = None
Things I did do, would be to sublcass models.Manager, produce a
safe_get such as the code above and employ that manager for my models. That method for you to write: SomeModel.objects.safe_get(foo='bar')
DoesNotExistexception if the object wasn't found for that given parameters. This exception can also be a characteristic from the model class. The
DoesNotExistexception gets from
You are able to catch the exception and assign
None to visit.
from django.core.exceptions import ObjectDoesNotExist try: go = Content.objects.get(name="baby") except ObjectDoesNotExist: go = None;