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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Overriding get_queryset lets you scope and shape the data a generic view exposes.
- 2Chaining select_related avoids N+1 queries by eager-loading related rows.
- 3Validating query params against a known set keeps user input from reaching the ORM unchecked.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
ruby
require "openssl" require "base32" class TOTP
How TOTP one-time codes work in Ruby
hmac
authentication
totp
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-scoped-filtered-listview-in-django-explained-python-a4f7/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.