What's the best way to handle Django's objects.get?
Solution 1:
try:
thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
thepost = None
Use the model DoesNotExist exception
Solution 2:
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.
Solution 3:
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."
Solution 4:
Another way of writing:
try:
thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
thepost = None
is simply:
thepost = Content.objects.filter(name="test").first()
Note that the two are not strictly the same. Manager method get
will raise not only an exception in the case there's no record you're querying for but also when multiple records are found. Using first
when there are more than one record might fail your business logic silently by returning the first record.
Solution 5:
Catch the exception
try:
thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
thepost = None
alternatively you can filter, which will return a empty list if nothing matches
posts = Content.objects.filter(name="test")
if posts:
# do something with posts[0] and see if you want to raise error if post > 1