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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
If you had to write an API to fetch a particular Record object using the id field. It would look something like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
These 4 lines of code can be converted into a single line of code using get_object_or_404:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
I write about navigating my life around being a technical co-founder of a startup, leveraging Django to build SaaS products and leading a wholesome life. Subscribe to my weekly newsletter to get notified on new content published every Sunday. I promise to deliver value and not BS 😌