Django Check if Object is Instance of Model

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


Hi Dev,

Here, I will show you django check if object is instance of model. We will look at example of check if object exists in django. Here you will learn django check if model exists in database. I explained simply step by step check if object is in queryset django. Follow bellow tutorial step of django model check if object exists.

So, we can use the exists() method to check if an object exists in the model in django. The exists() function can be used for different situations, but we use it with the if condition.

Here i explained simply step by step example of how to check if object is instance of model.

Django Admin Interface:



Example

In this example we will use the same Employee model. to get the Get employees with exists() method check the the records is exists in model instances get the object.

views.py
from django.http import HttpResponse
from core.models import Employee

def index(request):
    employees = Employee.objects.all()
    if employees.exists():
        return HttpResponse('object found')
    else:
        return HttpResponse('object not found')

So, Before running the server, we need to make sure that we have added the URL in the urls.py file. When we hit the URL, it will pull out the defined function from the views.py file, and in our case, we defined the index function.

Output
object found

To handle a missing object from a dynamic URL, we can utilize the get_object_or_404 class. When we are endeavoring to utilize an object that does not subsist, we visually perceive an exception that is not utilizer-cordial.

We can show the utilizer (page not found) error in lieu of the built-in Django exception; it will be a valid error. To utilize this error, we took an example code to raise an error if the Django server fails to find the object.

views.py
from django.http import Http404
from django.shortcuts import render

def dynamic_loockup_view(request,id):
    try:
        obj = Product.objects.get(id=id)
    except Product.DoesNotExist:
        # raise an exception "page not found"
        raise Http404
    OUR_CONTEXT = {
        "object": obj
    }
    return render(request,"products/product_detail.html",OUR_CONTEXT)

It is going to raise a 404 page error.



I hope it will help you....