What's the best way to handle Django's objects.get?


Question

Whenever I do this:

thepost = Content.objects.get(name="test")

It always throws an error when nothing is found. How do I handle it?

1
41
12/4/2010 10:50:08 AM

Accepted Answer

try:
    thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
    thepost = None

Use the model DoesNotExist exception

71
9/25/2018 9:42:20 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon