How to use ObjectDoesNotExist and DoesNotExist in Django?

In Django, ObjectDoesNotExist and DoesNotExist are exception classes that are typically used to catch instances where an object does not exist during a database query.

ObjectDoesNotExist is an exception class from django.core.exceptions that is used to catch the situation when an object is not found during a single object query. For example:

from django.core.exceptions import ObjectDoesNotExist
from myapp.models import MyModel

try:
    obj = MyModel.objects.get(id=1)
except ObjectDoesNotExist:
    print("Object does not exist")

DoesNotExist is an exception class from django.core.exceptions.DoesNotExist, typically used to catch the scenario where a query set returns no objects. For example:

from django.core.exceptions import DoesNotExist
from myapp.models import MyModel

try:
    obj = MyModel.objects.filter(name='myname').get()
except DoesNotExist:
    print("Object does not exist")

When using these two exception classes, it is common to capture exceptions in a try-except statement after a database query to handle cases where the object does not exist.

bannerAds