← Back to Django, page 5

django-0092 · Hard senior

How do you add conditional GET support with ETag and Last-Modified in Django to save bandwidth and server work?

The condition, require_safe, etag and last_modified decorators in django.views.decorators.http compare the client's If-None-Match or If-Modified-Since with values computed cheaply (a version number or max updated timestamp), and return 304 Not Modified without running the view body when nothing changed. ConditionalGetMiddleware can add ETag headers from the response body, saving bandwidth but not view work. For writes, If-Match gives optimistic concurrency.

Full answer

HTTP lets a client revalidate a cached copy: it sends If-None-Match: "<etag>" or If-Modified-Since: <date>; if the resource is unchanged, the server returns 304 Not Modified with no body.

In Django:

python
def timetable_etag(request, class_id):
    version = Timetable.objects.filter(class_room=class_id).aggregate(m=Max("updated"))["m"]
    return f'"{class_id}-{version:%Y%m%d%H%M%S%f}"' if version else None

@condition(etag_func=timetable_etag)
def timetable(request, class_id): ...

Key points:

  • The etag_func and last_modified_func must be cheaper than the view: one indexed aggregate or a version column, not a full render. Otherwise you only save bandwidth.
  • Return None to skip conditional handling (for example, the object does not exist).
  • @etag, @last_modified and @condition also handle If-Match and If-Unmodified-Since for unsafe methods, answering 412 Precondition Failed. This allows optimistic concurrency control for updates.
  • ConditionalGetMiddleware computes an ETag from the rendered body if none was set, and answers 304 when it matches. It saves transfer, not computation, because the view already ran.
  • Add Cache-Control (max-age, private or public) and Vary appropriately: ETag alone makes clients revalidate each time (cheap but still a round trip). cache_control and vary_on_headers decorators help.
  • ETags can be strong ("abc", byte-identical) or weak (W/"abc", semantically equal). Compression middleware may change strong ETags, so weak validators are common behind gzip.
  • Do not use ETags to hide per-user data from caches; combine with private and Vary: Cookie, Authorization.
  • DRF: use the same decorators on views, or implement get_object plus custom headers.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    ROOT_URLCONF=__name__,
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import datetime

from django.http import HttpResponse
from django.test import Client
from django.urls import path
from django.utils.http import http_date
from django.views.decorators.cache import cache_control
from django.views.decorators.http import condition

DATA = {"version": 3, "updated": datetime.datetime(2026, 12, 1, 9, 0, tzinfo=datetime.timezone.utc), "renders": 0}


def etag_func(request):
    return f'"timetable-v{DATA["version"]}"'


def last_modified_func(request):
    return DATA["updated"]


@cache_control(private=True, max_age=0)
@condition(etag_func=etag_func, last_modified_func=last_modified_func)
def timetable(request):
    DATA["renders"] += 1                      # the expensive work only runs when the client's copy is stale
    return HttpResponse(f"timetable version {DATA['version']}")


urlpatterns = [path("timetable/", timetable)]

c = Client()
r = c.get("/timetable/")
print(r.status_code, r["ETag"], r["Last-Modified"], r["Cache-Control"])
r2 = c.get("/timetable/", headers={"If-None-Match": r["ETag"]})
print(r2.status_code, repr(r2.content), "renders:", DATA["renders"])
r3 = c.get("/timetable/", headers={"If-Modified-Since": http_date(DATA["updated"].timestamp())})
print(r3.status_code, "renders:", DATA["renders"])

DATA["version"] = 4
DATA["updated"] += datetime.timedelta(hours=1)
r4 = c.get("/timetable/", headers={"If-None-Match": r["ETag"]})
print(r4.status_code, r4.content, "renders:", DATA["renders"])
r5 = c.put("/timetable/", headers={"If-Match": '"timetable-v3"'})
print("stale If-Match on PUT:", r5.status_code)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 "timetable-v3" Tue, 01 Dec 2026 09:00:00 GMT private, max-age=0 304 b'' renders: 1 304 renders: 1 200 b'timetable version 4' renders: 2 stale If-Match on PUT: 412

Key points

  • Client revalidates with If-None-Match or If-Modified-Since; server returns 304
  • Validator functions must be cheaper than the view
  • condition() also supports If-Match for 412 on updates
  • ConditionalGetMiddleware saves bandwidth, not computation
  • Combine with Cache-Control and Vary; protect per-user data

Common mistakes

  • Computing the ETag by rendering the whole response, saving nothing
  • Using last_modified with second precision for rapidly changing data
  • Caching per-user responses without private and Vary
  • Assuming ConditionalGetMiddleware avoids running the view

Follow-ups

  • How would you use If-Match to prevent lost updates?
  • What is the difference between strong and weak ETags?
  • How do CDNs treat these headers?

Tips

  • State that validators must be cheap
  • Mention 304 and 412
  • Differentiate middleware from decorators