Performance: DetailView for single objects
This affects the page load speed and rendering performance by how efficiently the server fetches and renders a single object detail page.
Jump into concepts and practice - no test required
from django.views.generic.detail import DetailView from .models import Product class ProductDetailView(DetailView): model = Product template_name = 'product_detail.html' context_object_name = 'product' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['related_items'] = Product.objects.filter(category=self.object.category) return context
from django.shortcuts import render from .models import Product def product_detail(request, pk): product = Product.objects.get(pk=pk) related_items = Product.objects.filter(category=product.category) return render(request, 'product_detail.html', {'product': product, 'related_items': related_items})
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual view with multiple queries | N/A (server-side) | N/A | N/A | [X] Bad |
| Django DetailView with optimized queries | N/A (server-side) | N/A | N/A | [OK] Good |
DetailView?DetailView?model in lowercase to specify the model class.Model, plural models, or model_name are not recognized by DetailView.path('product/<int:pk>/', ProductDetailView.as_view(), name='product-detail')class ProductDetailView(DetailView):
model = Product
template_name = 'product_detail.html'ProductDetailView display when visiting /product/5/?<int:pk> which passes primary key 5 to the view.class ArticleDetailView(DetailView):
model = Article
template = 'article_detail.html'template_name, not template.pk by default. To use slug, set slug_url_kwarg = 'slug' if your URL kwarg is 'slug'. The slug_field defaults to 'slug' and usually does not need to be set unless your model field is named differently.model = BlogPost and slug_url_kwarg = 'slug'; in URL use path('blog/<slug:slug>/', ...) correctly sets slug_url_kwarg to match the URL kwarg and uses the default slug_field. In the view, set model = BlogPost and slug_field = 'slug'; in URL use path('blog/<slug:slug>/', ...) incorrectly sets slug_field which is the model field name, not the URL kwarg. In the view, set model = BlogPost and pk_url_kwarg = 'slug'; in URL use path('blog/<slug:slug>/', ...) misuses pk_url_kwarg. In the view, set model = BlogPost and slug_field = 'slug'; in URL use path('blog/<int:slug>/', ...) uses wrong URL converter.model = BlogPost and slug_url_kwarg = 'slug'; in URL use path('blog/<slug:slug>/', ...) -> Option D