0 day streak
python / beginner
Snippet

Safe Object Retrieval

The get_object_or_404 shortcut is a clean way to fetch a single database record. If the record does not exist, it automatically raises a 404 Http error.

snippet.py
python
1
2
3
4
5
from django.shortcuts import get_object_or_404
from .models import Product
def detail(request, product_id):
item = get_object_or_404(Product, pk=product_id)
django
Breakdown
1
from django.shortcuts import get_object_or_404
Imports the helper function that combines a database query with error handling.
2
item = get_object_or_404(Product, pk=product_id)
Attempts to find a Product where the primary key (pk) matches product_id, or stops execution with a 404 page.