python 26 lines · 7 steps

Building a scoped, filtered ListView in Django

A class-based ListView that restricts invoices to the current user, eager-loads relations, and applies optional status filtering.

Explained by highlit
1from django.contrib.auth.mixins import LoginRequiredMixin
2from django.views.generic import ListView
3 
4from .models import Invoice
5 
6 
7class InvoiceListView(LoginRequiredMixin, ListView):
8 model = Invoice
9 template_name = "invoices/invoice_list.html"
10 context_object_name = "invoices"
11 paginate_by = 25
12 
13 def get_queryset(self):
14 queryset = (
15 super()
16 .get_queryset()
17 .filter(owner=self.request.user)
18 .select_related("client")
19 .order_by("-issued_at")
20 )
21 
22 status = self.request.GET.get("status")
23 if status in {"draft", "sent", "paid", "overdue"}:
24 queryset = queryset.filter(status=status)
25 
26 return queryset
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Overriding get_queryset lets you scope and shape the data a generic view exposes.
  2. 2Chaining select_related avoids N+1 queries by eager-loading related rows.
  3. 3Validating query params against a known set keeps user input from reaching the ORM unchecked.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a scoped, filtered ListView in Django — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code