Full answer
In a view such as /books/42/, the ID comes from the visitor. If book 42 does not exist, Book.objects.get(pk=42) raises Book.DoesNotExist. An unhandled exception becomes a 500 Internal Server Error, which is wrong: the server is fine, the resource is missing.
get_object_or_404 fixes that in one line:
book = get_object_or_404(Book, pk=pk)Under the hood it calls queryset.get(**kwargs) and catches DoesNotExist, raising Http404 instead. Django's handler turns Http404 into a 404 response (your 404.html when DEBUG=False). It does not catch MultipleObjectsReturned, so use unique lookups.
Pass a QuerySet to add conditions:
book = get_object_or_404(Book.objects.filter(is_published=True), slug=slug)
loan = get_object_or_404(Loan, pk=pk, member=request.user)The second line is an important security habit. Scoping by owner stops one member from reading another's loan by changing the ID in the URL (an insecure direct object reference, or IDOR). Returning 404 rather than 403 also avoids confirming that the record exists.
There is an async version for async views: aget_object_or_404 (Django 5.0+).
Keep it in views. In service functions that are not tied to HTTP, raise or handle DoesNotExist directly, because Http404 is an HTTP concept.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
from django.http import Http404
from django.shortcuts import get_object_or_404
class Loan(models.Model):
member = models.CharField(max_length=30)
book = models.CharField(max_length=60)
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Loan)
Loan.objects.create(member="anil", book="Malgudi Days")
Loan.objects.create(member="sara", book="The Guide")
print(get_object_or_404(Loan, pk=1).book)
for who, pk in [("anil", 99), ("anil", 2)]:
try:
get_object_or_404(Loan, pk=pk, member=who)
except Http404 as exc:
print(f"{who} asking for loan {pk}: 404 ({exc})")
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): Malgudi Days anil asking for loan 99: 404 (No Loan matches the given query.) anil asking for loan 2: 404 (No Loan matches the given query.)
Key points
- Turns DoesNotExist into Http404, so visitors see 404, not 500
- Accepts a model, manager or QuerySet
- Scope by owner to prevent IDOR
- MultipleObjectsReturned is not caught
- aget_object_or_404 exists for async views (Django 5.0+)
Common mistakes
- Using objects.get() in views and returning 500 for bad IDs
- Looking up by ID only, so users can read other users' records
- Expecting it to handle MultipleObjectsReturned
- Raising Http404 inside non-HTTP service code
Follow-ups
- What is an IDOR vulnerability?
- How do you customise the 404 page?
- When would 403 be better than 404?
Tips
- Say why a missing record is a 404 and not a 500
- Show the owner-scoped version, it signals security awareness
- Mention the async variant for Django 5