Use get_object_or_404 in Django to write lesser code

Django has a few nifty shortcuts that can be used to make your life easier. The get_object_or_404 method is one of them.

I always believe that as a software developer, one should write as little code as possible and this method helps you do the same.

What is get_object_or_404 in Django?

To put it simply, it is a shortcut that can save you the trouble of writing redundant code every time you need to query a particular object from the database.

An API that needs to retrieve an object from the database usually works in this way: If the object exists, return it and if not, return a 404 status code.

For the sake of an example, let us consider a model called Record that is defined as follows:

from django.db import models

class Record(models.Model):
  # id will be created automatically
  name = models.CharField(max_length=255)
  created_at = models.DateTimeField(auto_now_add=True)
  is_deleted = models.BooleanField(default=False)

If you had to write an API to fetch a particular Record object using the id field. It would look something like this:

from rest_framework import generics
from .models import Record
from django.http import Http404


class RecordRetrieveView(generics.RetrieveAPIView):
    serializer_class = RecordSerializer

    def get_object(self):
        try:
          return Record.objects.get(id=self.request.query_params['id'])
        except Record.DoesNotExist:
          raise Http404()

These 4 lines of code can be converted into a single line of code using get_object_or_404:

from rest_framework import generics
from django.shortcuts import get_object_or_404

class RecordRetrieveView(generics.RetrieveAPIView):
    serializer_class = RecordSerializer

def get_object(self):
    return get_object_or_404(Record, id=self.request.query_params['id'])



    Enter fullscreen mode
    


    Exit fullscreen mode




TL;DR

To retrieve objects from a database, use get_object_or_404 as opposed to getting the object using the ORM way and throwing an exception if it does not exist. This method pretty much does the same thing under the hood.

22