Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

Whenever I do this:

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

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

like image 831
TIMEX Avatar asked Dec 04 '10 10:12

TIMEX


People also ask

What does model objects all return?

Contact.objects.all() returns url, email, person and ID of row in Bonus.

How can I get objects in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What is a QuerySet?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


3 Answers

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

Use the model DoesNotExist exception

like image 84
4 revs, 4 users 59% Avatar answered Oct 19 '22 11:10

4 revs, 4 users 59%


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.

like image 27
Rob Golding Avatar answered Oct 19 '22 11:10

Rob Golding


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."
like image 31
zobbo Avatar answered Oct 19 '22 12:10

zobbo