What's the best way to handle Django's objects.get?
try:
thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
thepost = None
Use the model DoesNotExist exception
Often, it is more useful to use the Django shortcut function get_object_or_404
instead of the API directly:
from django.shortcuts import get_object_or_404
thepost = get_object_or_404(Content, name='test')
Fairly obviously, this will throw a 404 error if the object cannot be found, and your code will continue if it is successful.
You can also catch a generic DoesNotExist. As per the docs at http://docs.djangoproject.com/en/dev/ref/models/querysets/
from django.core.exceptions import ObjectDoesNotExist
try:
e = Entry.objects.get(id=3)
b = Blog.objects.get(id=1)
except ObjectDoesNotExist:
print "Either the entry or blog doesn't exist."