Django Models get_object_or_404 Method Example

Published On: 30/08/2022 | Category: Django


Hi Dev,

This article goes in detailed on django models get_object_or_404 method example. if you have question about how to use django get_object_or_404 then I will give simple example with solution. step by step explain django get_object_or_404 message. I explained simply about django get_object_or_404 custom message. Let's get started with django models get_object_or_404.

What is Django get_object_or_404 is a method that returns a 404 error if the object does not exist.

let's see bellow example here you will learn django models get_object_or_404 example.

Step 1: Create a Model

In this step now go for the models we will We'll call our single model Comments and it will have just two fields: name, comment and date. And finally set __str__ to display the name of the comments.

core/models.py
from django.db import models

class Comments(models.Model):
    name = models.CharField(max_length=300)
    comment = models.TextField()
    date = models.DateField(auto_now_add=False)

    def __str__(self):
        return self.name

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python manage.py makemigrations
python manage.py migrate

Adding some records:



Step 2: Creating the Views

In this step, Let's try to get a record that's not exists with the get() method and see what happens. open the views.py file and add:

views.py
from django.shortcuts import render
from .models import Comments
from django.http import HttpResponse

# Create your views here.
def get_comment(request):

    #get comment pk = 111
    obj = Comments.objects.get(pk=111)
    return HttpResponse(obj)
Output

In this step, let's do the same thing but now with the get_object_or_404 method and see the difference. open the views.py file and add:

If you want to get an object and you don't want to get an error when the record doesn't exist, you should use the get_object_or_404 method

views.py
from django.shortcuts import get_object_or_404
from .models import Comments
from django.http import HttpResponse

# Create your views here.
def get_comment(request):

    #get comment idpk = 111
    obj = get_object_or_404(Comments, pk=111)
    return HttpResponse(obj)

Output

Step 3: Customizing Django get_object_or_404 message

In this last As you know, we can't customize the get_object_or_404 method's error, but we can do it with the Http404 exception, let's see an example.

views.py
from django.http import Http404

def get_comment(request):
    try:
        obj = Comments.objects.get(pk=111)
    except Comments.DoesNotExist:
        raise Http404("the obj does not exist.")
Output

I Hope It will help you....