Saturday, October 4, 2025
HomeLanguagesget_object_or_404 method in Django Models

get_object_or_404 method in Django Models

Some functions are hard as well as boring to code each and every time. But Django users don’t have to worry about that because Django has some awesome built-in functions to make our work easy and enjoyable. Let’s discuss get_object_or_404() here.

What is get_object_or_404 in Django?

get_object_or_404 is a convenient shortcut function provided by Django, which is used for getting an object from a database using a model’s manager and raising an Http404 exception if the object is not found. It’s commonly used in views to get a single object based on a query and handle the case where the object doesn’t exist.

How to use get_object_or_404() in a Django Project?

This function calls the given model and gets an object from that if that object or model doesn’t exist it raises a 404 error.

Example: Suppose we want to fetch 3rd product from the product model then we can use:

Python3




# import get_object_or_404()
from django.shortcuts import get_object_or_404
 
 
# defining view
def product_view(request):
    # retrieving product (pk is primary key)
    product = get_object_or_404(Products, pk=3)


This is the advantage of Django if you hardcode that then you have to write this much line of code.

Python3




# import Http404
from django.http import Http404
 
 
# defining view
def product_view(request):
 
    # try except logic
    try:
        product = Products.objects.get(pk=1)
    except Products.DoesNotExist:
        raise Http404("Given query not found....")


Using get_object_or_404() with QuerySet

QuerySet instance is used to filter data while fetching from the database. For example, we want to fetch only shoes then we can write:

queryset = Products.objects.filter(type='shoes')
get_object_or_404(queryset)

We can simplify above example by a single line:

get_object_or_404(Products, type='shoes') 
RELATED ARTICLES

Most Popular

Dominic
32336 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6705 POSTS0 COMMENTS
Nicole Veronica
11870 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11934 POSTS0 COMMENTS
Shaida Kate Naidoo
6821 POSTS0 COMMENTS
Ted Musemwa
7086 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6778 POSTS0 COMMENTS