liveBook · Manning

Get_object_or_404

As explained in Django in Action

get_object_or_404 is a Django shortcut that retrieves an object matching query criteria or raises Http404 when no matching object exists.

get_object_or_404 is Django’s shortcut for fetching one database object while handling missing or invalid results as a 404 response. It keeps a view focused on the successful path: find the object, pass it to a template, and let Django stop the request when the lookup fails. section 4.12 section 4.6.1

A detail page usually receives an identifier from the URL. The view supplies the model and lookup criteria, commonly id=object_id. If exactly one object matches, the view continues; if none or multiple match, Django raises Http404 and displays a 404 page instead. section 4.6.1

The request flow is short:

  • A URL pattern captures an integer such as musician_id. section 4.6.1
  • The view calls get_object_or_404(Musician, id=musician_id). section 4.6.1
  • A successful lookup supplies the musician object to the template. section 4.6.1
  • A bad public URL becomes a 404 instead of an unhandled view failure. section 4.6.1
Listing 4.4 A view for displaying a Musician object based on an argument
# RiffMates/bands/views.py
from django.shortcuts import render, get_object_or_404  #1

from bands.models import Musician  #2

def musician(request, musician_id):
    musician = get_object_or_404(Musician, id=musician_id)  #3

    data = {
        "musician": musician, #4
    }

    return render(request, "musician.html", data)

The complete view shows the essential pattern: import the shortcut, look up the model with the captured ID, build template data, and render the detail page. section 4.6.1

A musician detail URL

With the route bands/musician/<int:musician_id>/, a request such as /bands/musician/100/ reaches the musician view. If no Musician has ID 100, the shortcut raises Http404 and Django returns a page-not-found response rather than rendering musician.html. section 4.6.1

How Django in Action covers it

How deep it goes
Explains model and criteria arguments, successful rendering, and Http404 behavior without descending into shortcut internals.
Examples
Uses a Musician detail view, an integer musician_id route, and missing ID 100 as the failing case.
What it assumes
Assumes basic Django URL, view, model, and template concepts while teaching defensive handling of user-supplied identifiers.
What you can do after
Apply it via Django to build detail views that render found objects and return 404 responses for invalid lookups.
How it connects
Connects Django ORM get-style queries with URL patterns, views, templates, and Http404 responses.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.