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

120๐Ÿ‘

โœ…

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

Use the model DoesNotExist exception

37๐Ÿ‘

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.

๐Ÿ‘คRob Golding

18๐Ÿ‘

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."
๐Ÿ‘คzobbo

12๐Ÿ‘

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.

๐Ÿ‘คRafael Valverde

8๐Ÿ‘

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
๐Ÿ‘คAnurag Uniyal

4๐Ÿ‘

Handling exceptions at different points in your views could really be cumbersome..What about defining a custom Model Manager, in the models.py file, like

class ContentManager(model.Manager):
    def get_nicely(self, **kwargs):
        try:
            return self.get(kwargs)
        except(KeyError, Content.DoesNotExist):
            return None

and then including it in the content Model class

class Content(model.Model):
    ...
    objects = ContentManager()

In this way it can be easily dealt in the views i.e.

post = Content.objects.get_nicely(pk = 1)
if post != None:
    # Do something
else:
    # This post doesn't exist

4๐Ÿ‘

There are essentially two ways you can do this. The first approach is more verbose as it doesnโ€™t use any shortcuts:

from django.http import Http404
from .models import Content    


try:
    thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
    raise Http404("Content does not exist")

Now since this sort of operation (i.e. get an object or raise 404 if it does not exist) is quite common in Web Development, Django offers a shortcut called get_object_or_404 that will get() the requested object or raise Http404 in case it is not found:

from django.shortcuts import get_object_or_404
from .models import Content


thepost = get_object_or_404(Content, name="test")

Likewise for lists of objects, you can use get_list_or_404() function that makes use of filter() instead of get() and in case the returned list is empty, Http404 will be raised.

3๐Ÿ‘

Raising a Http404 exception works great:

from django.http import Http404

def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
๐Ÿ‘คBanjer

Leave a comment