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:



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



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



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.