HOWTO · Django
How to Check if Object Exists in Django
In this explanation of the common issue you see how to check if an object exists in the model and you also learn how to handle exceptions to show the convenient error to the user.
On this page
Use a filtered Django queryset to check whether a row matches your criteria, retrieve it when you need its fields, and return a 404 for a missing object in a request. QuerySet.exists() answers the first question; get_object_or_404() and DoesNotExist cover common missing-object handling.
Check whether a queryset has a matching row with exists()
Call exists() on the queryset that represents the records you care about. For example, Product.objects.filter(pk=product_id).exists() returns True when that filtered queryset contains a row and False otherwise. It is a QuerySet method, not a general-purpose function, and filtering matters: Product.objects.all().exists() checks whether any product exists, not whether a particular product exists.
Use this check when the answer is only yes or no, such as deciding whether to show an action or avoid creating a duplicate. Django can issue a query optimized for checking existence. If you will immediately retrieve or iterate over the same rows, skip a separate existence check and use that result directly; otherwise the check can add another database query.
Retrieve one matching object and handle DoesNotExist
When the next step needs the object’s fields, use Product.objects.get(pk=product_id). get() expects exactly one matching row: if there is no match, it raises Product.DoesNotExist; if multiple rows match, it raises Product.MultipleObjectsReturned. Use a unique key such as a primary key when the code expects one object. Catch the model-specific DoesNotExist only when your application can respond meaningfully; otherwise let the error surface rather than silently treating an unexpected condition as success.
This distinction helps choose the right operation: exists() gives a Boolean, while get() gives you an object or signals that the lookup did not produce exactly one object. A check followed by get() can also race with another database change, so avoid treating the earlier Boolean as a guarantee that the later retrieval will succeed.
Return a 404 when an object is missing
For a request-driven lookup, Django’s get_object_or_404() function is the concise option. For example, product = get_object_or_404(Product, pk=product_id) retrieves the matching product and raises Http404 if it does not exist. The framework then renders its normal not-found response. Import the helper from django.shortcuts and use it in a view where a missing resource should be reported as not found.
You can handle the lookup explicitly when the view needs custom behavior: call Product.objects.get(pk=product_id) inside try, catch Product.DoesNotExist, and raise Http404. Import Http404 from django.http. This translates the model lookup failure into an HTTP response while keeping the successful path’s product available to the rest of the view. Do not catch a broad exception; unrelated programming or database errors should not be disguised as a missing page.
Test the found and missing cases
Exercise both outcomes using a known existing identifier and one that is not present. The following plain Python illustration shows the Boolean decision with in-memory records; it is not a Django ORM test. In a Django test, create a Product, assert that a filtered queryset’s exists() is true for its primary key, then assert false for an unused key. For retrieval, assert the created object is returned and that Product.DoesNotExist is raised for the unused key. For a view using get_object_or_404(), test a successful response for the existing product and a 404 response for the unused key.
Run this self-contained lookup example. It uses a list to make the decision visible; in a Django view, apply the same choice with a filtered queryset.
products = [{"id": 7, "name": "Notebook"}]
for requested_id in (7, 12):
matches = [product for product in products if product["id"] == requested_id]
print(bool(matches))
True
False
The first result represents a match and the second represents no match. The list stands in for the filtered records only; Django performs the lookup through the database, and its queryset methods should be used in application code.