← Interview prep

Django interview questions

Models, ORM, auth, and Django web patterns.

100 questions · Page 5 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 5 of 5

Questions 81–100 of 100 · 0 of 20 on this page marked learned

81.django-0081Mediummid

How do you integrate Celery with Django: configuration, defining tasks, calling them with delay(), retries and testing in eager mode?

Create a Celery app in the project, load its settings from Django settings with a CELERY_ namespace, define tasks with @shared_task, and call them with task.delay(args) or apply_async(). Tasks run in separate worker processes with a message broker such as Redis or RabbitMQ. Pass IDs, not objects, make tasks idempotent, use bind=True with self.retry() for transient failures, and run synchronously in tests with task_always_eager.

Full answer

Setup (conventional layout):

python
# proj/celery.py
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings")
app = Celery("proj")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()          # finds tasks.py in each installed app

# proj/__init__.py
from .celery import app as celery_app

Settings: CELERY_BROKER_URL, CELERY_RESULT_BACKEND (optional), CELERY_TASK_ACKS_LATE, time limits.

Tasks:

python
@shared_task(bind=True, autoretry_for=(ConnectionError,), retry_backoff=True, max_retries=3)
def send_receipt(self, payment_id):
    payment = Payment.objects.get(pk=payment_id)
    ...
  • @shared_task works without importing the app instance, so reusable apps can define tasks.
  • Call send_receipt.delay(payment.id); apply_async(args, countdown=60, queue="mail") gives control over delay and routing.
  • Arguments must be serialisable (JSON by default): pass primary keys and reload inside the task, so data is fresh and messages are small.
  • Queue after commit: transaction.on_commit(lambda: send_receipt.delay(payment.id)), otherwise the worker may run before the row is visible.
  • Retries: self.retry(exc=exc, countdown=...) or autoretry_for with retry_backoff. Tasks must be idempotent because retries and acks_late can run them more than once.
  • Do not wait for results inside a request; use the result backend only for tracking.

Testing: set CELERY_TASK_ALWAYS_EAGER = True so .delay() runs inline. CELERY_TASK_EAGER_PROPAGATES = True re-raises task exceptions in the test, but in the Celery version used for the snippet it also surfaced Retry instead of retrying, so leave it off when testing retry logic. Eager mode does not test serialisation, queues or concurrency, so also test task functions directly and run an occasional integration test with a real worker.

python
import sys

from celery import Celery, shared_task

app = Celery("demo")
app.conf.update(
    broker_url="memory://",
    task_always_eager=True,              # tests and demos: run inline, no worker or broker needed
)

attempts = {"n": 0}
SENT = []


@shared_task(bind=True, max_retries=3)
def send_receipt(self, payment_id):
    attempts["n"] += 1
    if attempts["n"] < 3:
        raise self.retry(exc=ConnectionError("mail server busy"), countdown=0)
    SENT.append(payment_id)
    return f"receipt sent for payment {payment_id}"


result = send_receipt.delay(42)
print(result.get(), "| attempts:", attempts["n"], "| sent:", SENT)


@shared_task
def add(x, y):
    return x + y


print(add.apply_async((2, 3), countdown=60).get(), add.delay(4, 5).get())
print(add.name, "| eager:", result.__class__.__name__)

import json
try:
    json.dumps({"student": object()})
except TypeError:
    print("task arguments must be JSON-serialisable: pass the id, not the object")

Standalone script. Needs `pip install celery`. It uses the in-memory broker with eager mode, so no Redis or worker is required; in a project the app lives in proj/celery.py and a worker runs with `celery -A proj worker`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3, Celery 5.7.0): receipt sent for payment 42 | attempts: 3 | sent: [42] 5 9 demo.add | eager: EagerResult task arguments must be JSON-serialisable: pass the id, not the object

Key points

  • Celery app loads Django settings with the CELERY_ namespace
  • @shared_task plus delay() or apply_async()
  • Pass IDs, not objects; make tasks idempotent
  • Queue with transaction.on_commit()
  • Eager mode for unit tests; real worker for integration tests

Common mistakes

  • Passing model instances as task arguments
  • Queuing a task inside a transaction before commit
  • Writing tasks that are unsafe to run twice
  • Waiting for task results inside web requests

Follow-ups

  • What does acks_late change?
  • How do you route tasks to different queues?
  • How do you schedule periodic tasks?

Tips

  • Show the Django integration lines
  • Say pass IDs and use on_commit
  • Mention idempotency
82.django-0082Mediummid

How do you test Django REST Framework endpoints with APIClient and APITestCase, including authentication, permissions and error cases?

APITestCase gives self.client, an APIClient that sends JSON by default with format='json' and supports force_authenticate(user) to skip real login. Tests should check status codes, the response body shape, permission boundaries (anonymous, normal user, owner, staff), validation errors and database side effects, using setUpTestData for shared fixtures and assertNumQueries for performance guards.

Full answer

rest_framework.test provides APIRequestFactory (build requests, call views directly), APIClient (full stack through URLs and middleware) and APITestCase (a Django TestCase with self.client = APIClient()).

Pattern:

python
class StudentApiTests(APITestCase):
    @classmethod
    def setUpTestData(cls):
        cls.teacher = User.objects.create_user("t", password="x", is_staff=True)
        cls.pupil = User.objects.create_user("p", password="x")

    def test_anonymous_gets_401(self):
        self.assertEqual(self.client.get("/api/students/").status_code, 401)

    def test_staff_can_create(self):
        self.client.force_authenticate(self.teacher)
        r = self.client.post("/api/students/", {"name": "Asha"}, format="json")
        self.assertEqual(r.status_code, 201)

Guidelines:

  • force_authenticate(user=..., token=...) bypasses authentication classes, which is fine for permission logic. Add a few tests with real credentials (client.credentials(HTTP_AUTHORIZATION="Bearer ...")) to prove the auth setup works.
  • Always send format="json" or set TEST_REQUEST_DEFAULT_FORMAT in settings; otherwise bodies are multipart.
  • Test the matrix: unauthenticated (401 or 403), forbidden user (403), owner (200), other user's object (404 or 403), invalid payload (400 with field errors).
  • Assert response JSON structure, not only status codes, and database state (Student.objects.count()).
  • assertNumQueries protects list endpoints against N+1 regressions.
  • self.client.logout() and force_authenticate(None) reset identity.
  • Test throttling by overriding DEFAULT_THROTTLE_RATES with override_settings and clearing the cache between tests.
  • Run tests in parallel with manage.py test --parallel and avoid shared global state.
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", "rest_framework", "rest_framework.authtoken", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import unittest

from django.contrib.auth import get_user_model
from django.db import models, connection
from django.test.utils import setup_test_environment
from django.urls import include, path
from rest_framework import serializers, viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.routers import DefaultRouter
from rest_framework.test import APITestCase


class Note(models.Model):
    owner = models.ForeignKey("auth.User", on_delete=models.CASCADE)
    text = models.CharField(max_length=100)

    class Meta:
        app_label = "school"


class NoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Note
        fields = ["id", "text"]


class NoteViewSet(viewsets.ModelViewSet):
    serializer_class = NoteSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Note.objects.filter(owner=self.request.user).order_by("id")

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


router = DefaultRouter()
router.register("notes", NoteViewSet, basename="note")
urlpatterns = [path("api/", include(router.urls))]

User = get_user_model()
with connection.schema_editor() as editor:
    for m in (User, Note):
        editor.create_model(m)


class NoteApiTests(APITestCase):
    @classmethod
    def setUpTestData(cls):
        cls.asha = User.objects.create_user("asha", password="x")
        cls.ravi = User.objects.create_user("ravi", password="x")
        cls.note = Note.objects.create(owner=cls.asha, text="private")

    def test_anonymous_is_rejected(self):
        self.assertEqual(self.client.get("/api/notes/").status_code, 403)

    def test_owner_sees_own_note(self):
        self.client.force_authenticate(self.asha)
        r = self.client.get("/api/notes/")
        self.assertEqual([n["text"] for n in r.json()], ["private"])

    def test_other_user_gets_404(self):
        self.client.force_authenticate(self.ravi)
        self.assertEqual(self.client.get(f"/api/notes/{self.note.pk}/").status_code, 404)

    def test_create_sets_owner_and_validates(self):
        self.client.force_authenticate(self.ravi)
        r = self.client.post("/api/notes/", {"text": "mine"}, format="json")
        self.assertEqual((r.status_code, Note.objects.get(pk=r.json()["id"]).owner), (201, self.ravi))
        bad = self.client.post("/api/notes/", {"text": ""}, format="json")
        self.assertEqual((bad.status_code, list(bad.json())), (400, ["text"]))

    def test_list_uses_one_query(self):
        self.client.force_authenticate(self.asha)
        with self.assertNumQueries(1):
            self.client.get("/api/notes/")


setup_test_environment()
suite = unittest.defaultTestLoader.loadTestsFromTestCase(NoteApiTests)
result = unittest.TextTestRunner(verbosity=0, stream=open("/dev/null", "w")).run(suite)
print("ran:", result.testsRun, "failures:", len(result.failures), "errors:", len(result.errors))
for case, tb in result.failures + result.errors:
    print(case, tb[-300:])

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. Requires `pip install djangorestframework`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ran: 5 failures: 0 errors: 0

Key points

  • APIClient sends JSON with format='json'
  • force_authenticate skips login to test permissions
  • Test the full matrix: anonymous, forbidden, owner, other user, invalid
  • Assert body and database state, not only status
  • assertNumQueries guards against N+1

Common mistakes

  • Sending multipart bodies by forgetting format='json'
  • Testing only the happy path and status 200
  • Relying only on force_authenticate and never testing real credentials
  • Not checking that users cannot read or change other users' objects

Follow-ups

  • How do you test token or JWT authentication end to end?
  • How would you test throttling reliably?
  • What is the difference between APIRequestFactory and APIClient?

Tips

  • List the permission test matrix
  • Mention force_authenticate and credentials
  • Mention assertNumQueries
83.django-0083Mediummid

How do Django permissions and groups work, and what are the common pitfalls such as permission caching and superusers?

Every model gets add, change, delete and view permissions stored in the auth_permission table. Users get them directly or through groups, and user.has_perm("app.change_student") checks them. Superusers pass every check, inactive users pass none, and permissions are cached on the user object after the first check, so a changed permission is not seen until the user is re-fetched. Object-level permissions need an extra backend or your own rules.

Full answer

Model-level permissions:

  • makemigrations/migrate creates four permissions per model (add_, change_, delete_, view_) with codename like change_student and content type pointing at the model. Custom ones go in Meta.permissions = [("approve_result", "Can approve result")].
  • Check with user.has_perm("school.approve_result") (format app_label.codename), user.has_perms([...]), and in views with PermissionRequiredMixin, @permission_required, or in DRF with DjangoModelPermissions.
  • Assign directly with user.user_permissions.add(perm) or via a Group: group.permissions.add(perm), user.groups.add(group). Groups represent roles ("Teachers", "Registrars"), which is easier to manage than per-user permissions.
  • Rules: is_superuser=True returns True for everything; is_active=False returns False for everything (even for superusers); staff status only grants admin access, not permissions.

Caching pitfall: ModelBackend caches the permission set in user._perm_cache (and _user_perm_cache, _group_perm_cache) the first time you call has_perm. If you add a permission and check again on the same object, the answer is stale. Re-fetch the user (User.objects.get(pk=...)), which every new request does anyway, or delete the cache attributes in tests. This surprises people in tests and in long-running scripts.

Other points:

  • Permissions are created after migrations by the post_migrate signal. Data migrations that reference permissions must run after those exist or create them explicitly.
  • Do not hard-code permission primary keys; look up by content_type and codename.
  • has_perm triggers queries (cached afterwards); in templates, perms.school.change_student uses the same cache.
  • Object-level permissions (can this teacher edit this class?) are not built in. Use a package such as django-guardian, or implement has_object_permission in DRF or check ownership in get_queryset().
  • Prefer permission checks over is_staff or role-name string comparisons in code, and test with real groups.
  • Admin respects model permissions for each action, which is how read-only staff roles are built.
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
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.contrib.auth.models import Group, Permission, User
from django.core.management import call_command

call_command("migrate", verbosity=0)       # creates auth tables and the default permissions

asha = User.objects.create_user("asha", password="pw-123456")
perm = Permission.objects.get(content_type__app_label="auth", codename="change_group")
print("direct perm:", asha.has_perm("auth.change_group"))

asha.user_permissions.add(perm)
print("same object after add (stale cache):", asha.has_perm("auth.change_group"))   # the cache was filled by the first call
asha = User.objects.get(pk=asha.pk)
print("re-fetched user:", asha.has_perm("auth.change_group"))

teachers = Group.objects.create(name="Teachers")
teachers.permissions.add(Permission.objects.get(content_type__app_label="auth", codename="view_group"))
ravi = User.objects.create_user("ravi", password="pw-123456")
ravi.groups.add(teachers)
ravi = User.objects.get(pk=ravi.pk)
print("via group:", ravi.has_perm("auth.view_group"), "| not granted:", ravi.has_perm("auth.delete_group"))

root = User.objects.create_superuser("root", password="pw-123456")
print("superuser:", root.has_perm("auth.delete_group"))
root.is_active = False
print("inactive superuser:", root.has_perm("auth.delete_group"))
print("codenames for auth.group:", sorted(Permission.objects.filter(content_type__model="group").values_list("codename", flat=True)))

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. It runs migrate on an in-memory SQLite database to create the auth tables and default permissions. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): direct perm: False same object after add (stale cache): False re-fetched user: True via group: True | not granted: False superuser: True inactive superuser: False codenames for auth.group: ['add_group', 'change_group', 'delete_group', 'view_group']

Key points

  • Four default permissions per model; custom ones in Meta.permissions
  • Users get permissions directly or via groups; prefer groups
  • Superuser passes everything; inactive user passes nothing
  • has_perm caches on the user object, so re-fetch after changes
  • Object-level permissions need extra logic or a package

Common mistakes

  • Hard-coding permission primary keys
  • Expecting has_perm to see a change on a user object that already checked
  • Using is_staff as an authorization check
  • Forgetting that an inactive user fails every check, even a superuser
  • Granting permissions per user instead of through groups

Follow-ups

  • How would you implement object-level permissions?
  • How do DRF permission classes use these permissions?
  • How do you create groups and permissions in a data migration?

Tips

  • Recite the four default codenames
  • Mention the cache pitfall
  • Say groups over per-user grants
84.django-0084Mediummid

How do file uploads work in Django, and how do you validate, name and store them safely with FileField and storage backends?

Uploaded files arrive in request.FILES as UploadedFile objects (kept in memory when small, spooled to a temporary file when large). A FileField saves them through a storage backend, configured with STORAGES (FileSystemStorage by default, S3 and others through packages). Validate size, extension and real content, generate your own names in upload_to instead of trusting the client filename, serve user files from a separate domain or with forced downloads, and use object storage in production.

Full answer

Flow: the browser sends multipart/form-data with enctype; Django parses it into request.FILES. Files below FILE_UPLOAD_MAX_MEMORY_SIZE (2.5 MB) stay in memory (InMemoryUploadedFile), larger ones go to a temp file (TemporaryUploadedFile). DATA_UPLOAD_MAX_MEMORY_SIZE limits non-file body size; there is no default upper limit for files, so enforce one at the proxy and in validators.

Model side:

python
def doc_path(instance, filename):
    ext = Path(filename).suffix.lower()
    return f"docs/{instance.owner_id}/{uuid4().hex}{ext}"

class Document(models.Model):
    file = models.FileField(upload_to=doc_path, validators=[validate_size, FileExtensionValidator(["pdf", "png"])])
  • upload_to can be a callable returning a path relative to storage root: use it to bucket by owner or date and to discard the client's name. Never build paths from filename directly: get_valid_name() and FileSystemStorage strip path separators, but you should still not trust names.
  • If a name already exists, Storage.get_available_name() appends a random suffix instead of overwriting.
  • Validators: FileExtensionValidator checks the extension only; also check size (file.size) and real type (magic bytes via python-magic, or open images with Pillow's verify()). Do not trust the content_type header.
  • Storage backends: configure STORAGES = {"default": {"BACKEND": ...}, "staticfiles": {...}} (Django 4.2+). Use django-storages for S3, GCS or Azure. Tests can use InMemoryStorage (Django 4.2+).
  • Serving: do not serve MEDIA_ROOT through Django in production. Use signed, expiring URLs from object storage, or X-Accel-Redirect style offloading for permission checks. Serve with Content-Disposition: attachment and from a separate domain to prevent stored XSS via HTML or SVG uploads.
  • Cleanup: deleting a model row does not delete the file. Remove it in post_delete (after commit) or use a periodic job to remove orphans.
  • Large files: use direct-to-bucket uploads via pre-signed URLs, then store the key.
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
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import tempfile
from pathlib import Path
from uuid import uuid4

from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage, InMemoryStorage
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.validators import FileExtensionValidator
from django.db import connection, models

root = Path(tempfile.mkdtemp())
disk = FileSystemStorage(location=str(root))


def validate_size(f):
    if f.size > 1024:
        raise ValidationError("File larger than 1 KB")


def doc_path(instance, filename):
    return f"docs/{instance.owner}/{uuid4().hex}{Path(filename).suffix.lower()}"      # client name is discarded


class Document(models.Model):
    owner = models.CharField(max_length=20)
    file = models.FileField(upload_to=doc_path, storage=disk,
                            validators=[validate_size, FileExtensionValidator(["pdf", "txt"])])

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Document)

doc = Document(owner="asha", file=SimpleUploadedFile("../../EVIL NAME.TXT", b"hello", content_type="text/plain"))
doc.full_clean()
doc.save()
print("stored under:", doc.file.name.startswith("docs/asha/"), doc.file.name.endswith(".txt"), "evil" not in doc.file.name.lower())
print("size and content:", doc.file.size, doc.file.read())

for name, data in [("script.exe", b"x"), ("big.txt", b"x" * 2000)]:
    bad = Document(owner="asha", file=SimpleUploadedFile(name, data))
    try:
        bad.full_clean()
    except ValidationError as exc:
        print(name, "->", exc.message_dict["file"])

# Deleting the row does not remove the file
path = Path(doc.file.path)
doc.delete()
print("file still on disk after row delete:", path.exists())
path.unlink()

mem = InMemoryStorage()          # handy in tests: nothing touches the disk
saved = mem.save("report.txt", ContentFile(b"abc"))
print("in-memory:", saved, mem.exists(saved), mem.open(saved).read())
second = mem.save("report.txt", ContentFile(b"def"))
print("collision gets a new name:", second != "report.txt", second.startswith("report_"))

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. Files are written to a temporary folder. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): stored under: True True True size and content: 5 b'hello' script.exe -> ['File extension “exe” is not allowed. Allowed extensions are: pdf, txt.'] big.txt -> ['File larger than 1 KB'] file still on disk after row delete: True in-memory: report.txt True b'abc' collision gets a new name: True True

Key points

  • request.FILES holds UploadedFile objects; large ones spool to disk
  • upload_to callable builds your own path and name
  • Validate size, extension and real content, not the client's header
  • Use STORAGES and django-storages; InMemoryStorage in tests
  • Deleting the row does not delete the file

Common mistakes

  • Using the client's filename in the storage path
  • Validating only the extension or content_type header
  • Serving user uploads from the app domain with inline HTML or SVG
  • Expecting deleting a row to delete the file
  • Forgetting to limit upload size at the proxy and in validators
  • Serving MEDIA_ROOT with Django in production

Follow-ups

  • How do pre-signed uploads to S3 work with Django?
  • How would you scan uploads for malware?
  • How do you process images asynchronously after upload?

Tips

  • Describe the upload flow
  • Show upload_to with a generated name
  • Mention cleanup of orphan files
85.django-0085Hardsenior

How do you write production-grade Django middleware that works in both sync and async mode, handles exceptions and short-circuits requests?

A middleware is a callable factory: __init__(get_response) and __call__(request). To work under both WSGI and ASGI, declare sync_capable and async_capable and, when get_response is a coroutine function, mark the instance with markcoroutinefunction and provide an async __call__. process_view and process_exception hooks add finer control, and returning a response early short-circuits the chain. Avoid blocking calls inside async middleware, because Django will otherwise adapt sync code through a thread pool at a cost.

Full answer

Django wraps middleware so that each layer can be sync or async. When a layer's mode differs from the next one, Django adapts through sync_to_async or async_to_sync threads, which adds overhead. So the best design is a middleware that is natively both.

Pattern:

python
class TimingMiddleware:
    sync_capable = True
    async_capable = True

    def __init__(self, get_response):
        self.get_response = get_response
        if iscoroutinefunction(get_response):
            markcoroutinefunction(self)

    def __call__(self, request):
        if iscoroutinefunction(self):
            return self.__acall__(request)
        ...
        return self.get_response(request)

    async def __acall__(self, request):
        ...
        return await self.get_response(request)

The @sync_and_async_middleware decorator offers function-style middleware with the same effect.

Hooks and flow:

  • __call__: code before get_response runs on the way in, code after on the way out. Returning a response without calling get_response short-circuits: later middleware and the view never run (maintenance mode, rate limiting, IP blocks).
  • process_view(request, view_func, args, kwargs): runs just before the view, after URL resolution; useful for per-view rules via decorators.
  • process_exception(request, exception): called when a view raises; return a response to handle it, or None to continue. It does not see exceptions raised in other middleware.
  • process_template_response: for responses with render().

Production rules: keep it fast (it runs for every request), do not read the body unless necessary (it breaks streaming and upload handlers), avoid blocking I/O in async mode, order carefully in MIDDLEWARE (security and sessions before auth), and keep per-request state on request or a ContextVar, never on the middleware instance (it is shared across requests).

Check adaptation with DEBUG logging: Django logs a debug line when it adapts a middleware to a different mode.

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__,
    MIDDLEWARE=["__main__.Guard", "__main__.Timing"],
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import asyncio
from asgiref.sync import iscoroutinefunction, markcoroutinefunction

from django.http import HttpResponse, JsonResponse
from django.test import AsyncClient, Client
from django.urls import path

trace = []


class Guard:
    """Short-circuits requests that carry X-Maintenance and turns view errors into JSON."""
    sync_capable = True
    async_capable = True

    def __init__(self, get_response):
        self.get_response = get_response
        if iscoroutinefunction(get_response):
            markcoroutinefunction(self)

    def __call__(self, request):
        if iscoroutinefunction(self):
            return self.__acall__(request)
        if "X-Maintenance" in request.headers:
            return HttpResponse("down for maintenance", status=503)
        return self.get_response(request)

    async def __acall__(self, request):
        if "X-Maintenance" in request.headers:
            return HttpResponse("down for maintenance", status=503)
        return await self.get_response(request)

    def process_exception(self, request, exception):
        trace.append(f"process_exception: {type(exception).__name__}")
        return JsonResponse({"error": "bad request data"}, status=400)


class Timing:
    sync_capable = True
    async_capable = True

    def __init__(self, get_response):
        self.get_response = get_response
        self.is_async = iscoroutinefunction(get_response)
        if self.is_async:
            markcoroutinefunction(self)

    def __call__(self, request):
        if self.is_async:
            return self.__acall__(request)
        trace.append("Timing (sync path)")
        return self.get_response(request)

    async def __acall__(self, request):
        trace.append("Timing (async path)")
        return await self.get_response(request)


def hello(request):
    return HttpResponse("hello")


def broken(request):
    raise ValueError("bad value")


async def ahello(request):
    return HttpResponse("hello from async view")


urlpatterns = [path("hello/", hello), path("broken/", broken), path("ahello/", ahello)]

c = Client()
print(c.get("/hello/").status_code, c.get("/hello/", headers={"X-Maintenance": "1"}).status_code)
print(c.get("/broken/").json())
print(trace)
trace.clear()


async def main():
    ac = AsyncClient()
    r = await ac.get("/ahello/")
    print(r.status_code, r.content)
    r = await ac.get("/ahello/", headers={"X-Maintenance": "1"})
    print(r.status_code)


asyncio.run(main())
print(trace)

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. The middleware classes live in the same file and are referenced through __main__. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 503 {'error': 'bad request data'} ['Timing (sync path)', 'Timing (sync path)', 'process_exception: ValueError'] 200 b'hello from async view' 503 ['Timing (async path)']

Key points

  • Declare sync_capable and async_capable; mark coroutine instances
  • Returning a response early short-circuits the stack
  • process_exception can turn view errors into responses
  • Never store per-request state on the middleware instance
  • Avoid blocking calls in async middleware

Common mistakes

  • Writing sync-only middleware and silently forcing thread adaptation on async stacks
  • Storing request data on self in the middleware instance
  • Reading request.body in middleware and breaking streaming uploads
  • Putting authentication-dependent middleware before SessionMiddleware

Follow-ups

  • How does process_view differ from decorating a view?
  • What happens to middleware order on the response path?
  • How do you test middleware in isolation with RequestFactory?

Tips

  • Explain sync_capable and async_capable
  • Describe short-circuiting
  • Warn about instance state
86.django-0086Hardsenior

How do custom Django signals work, and what are the pitfalls: dispatch_uid, weak references, send_robust, ordering and transactions?

A Signal object keeps receivers that are called synchronously by send(). Use dispatch_uid to prevent duplicate registration when a module is imported twice, remember receivers are held by weak reference by default (lambdas and local functions can vanish), choose send_robust() when one failing receiver must not break the sender, and never assume receiver order or transactional safety: post_save fires before the transaction commits, so use transaction.on_commit() for external effects.

Full answer

Signals decouple senders from receivers, but they hide control flow. Use them for cross-app notifications where the sender should not know the listeners; use plain function calls when you own both sides.

Custom signal:

python
fee_paid = Signal()                 # Django 3.0+ takes no providing_args
fee_paid.send(sender=Fee, instance=fee, amount=500)

@receiver(fee_paid, dispatch_uid="send_receipt_v1")
def send_receipt(sender, instance, amount, **kwargs): ...

Pitfalls:

  1. Duplicate registration: if the module that registers the receiver is imported under two names, or ready() runs twice in tests, the receiver is called twice. dispatch_uid makes the pair (signal, uid) unique.
  2. Weak references: connect() stores receivers weakly by default. A lambda or nested function is garbage-collected right away and never fires. Use module-level functions, or weak=False.
  3. Exceptions: send() stops at the first receiver exception and re-raises it, so one bad listener breaks the sender. send_robust() catches exceptions, returns [(receiver, response_or_exception)], and you should log failures.
  4. Order: receivers run in connection order, which depends on import order. Do not rely on it.
  5. Transactions: post_save runs inside the open transaction. If it sends an email or queues a task and the transaction later rolls back, the side effect already happened. Wrap external effects in transaction.on_commit().
  6. Bulk operations: bulk_create, update() and QuerySet.delete() fast paths skip many signals (post_save), so signals are not a complete audit mechanism.
  7. Registration location: connect receivers in AppConfig.ready() so they are imported once at startup.
  8. Performance: each signal adds calls on hot paths; filter early with sender=.

Alternatives: explicit service functions, model save() overrides for logic that is truly part of the model, and an outbox table for reliable events.

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
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import gc

from django.db import models, connection, transaction
from django.db.models.signals import post_save
from django.dispatch import Signal, receiver

fee_paid = Signal()
log = []


def receipt(sender, **kwargs):
    log.append("receipt")


def broken(sender, **kwargs):
    raise RuntimeError("mail server down")


def ledger(sender, **kwargs):
    log.append("ledger")


fee_paid.connect(receipt, dispatch_uid="receipt_v1")
fee_paid.connect(receipt, dispatch_uid="receipt_v1")          # duplicate import: ignored
fee_paid.connect(broken, dispatch_uid="broken_v1")
fee_paid.connect(ledger, dispatch_uid="ledger_v1")

print("receivers:", len(fee_paid.receivers))
try:
    fee_paid.send(sender="Fee")
except RuntimeError as exc:
    print("send() raised:", exc, "| log:", log)
log.clear()
results = fee_paid.send_robust(sender="Fee")
print("send_robust log:", log, "| errors:", [type(r).__name__ for _, r in results if isinstance(r, Exception)])

fee_paid.connect(lambda sender, **kw: log.append("lambda"), dispatch_uid="lam")   # weak reference to a temporary
gc.collect()
log.clear()
fee_paid.send_robust(sender="Fee")
print("lambda fired:", "lambda" in log)


class Fee(models.Model):
    amount = models.IntegerField()

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Fee)

emails = []


@receiver(post_save, sender=Fee, dispatch_uid="email_on_save")
def email_receipt(sender, instance, created, **kwargs):
    emails.append(f"sent immediately for {instance.amount}")                     # fires before commit
    transaction.on_commit(lambda: emails.append(f"sent after commit for {instance.amount}"))


try:
    with transaction.atomic():
        Fee.objects.create(amount=500)
        raise RuntimeError("payment gateway failed")
except RuntimeError:
    pass
print(Fee.objects.count(), emails)

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. In a test run on_commit callbacks are discarded by TestCase unless captured; here autocommit mode is used outside the failing atomic block. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): receivers: 3 send() raised: mail server down | log: ['receipt'] send_robust log: ['receipt', 'ledger'] | errors: ['RuntimeError'] lambda fired: False 0 ['sent immediately for 500']

Key points

  • send() is synchronous and stops on the first exception; send_robust() collects them
  • dispatch_uid prevents duplicate receivers
  • Receivers are weak references by default
  • post_save fires inside the transaction; use on_commit for side effects
  • Bulk operations skip many signals

Common mistakes

  • Registering receivers inside functions or with lambdas and losing them to garbage collection
  • Sending emails or tasks from post_save inside a transaction
  • Relying on receiver order or on signals for bulk operations
  • Letting one failing receiver break the sender without choosing send_robust

Follow-ups

  • When would you replace signals with an explicit service call?
  • Where should receivers be connected, and why?
  • What do pre_save and post_save get as arguments?

Tips

  • List 4 pitfalls
  • Say on_commit for side effects
  • Differentiate send and send_robust
87.django-0087Hardsenior

What does running Celery safely in production with Django involve: idempotent tasks, acks_late, retry policy, time limits, queues and monitoring?

Celery delivers tasks at least once, so every task must be idempotent. Production settings include acks_late (acknowledge after the task finishes, so worker crashes cause redelivery), bounded retries with backoff and jitter, hard and soft time limits, separate queues for slow and urgent work, prefetch tuned to task length, result expiry, and monitoring of queue depth and failure rates. Deduplicate with a unique business key, a database constraint or a cache lock.

Full answer

Delivery semantics: with the default acks_early, a message is acknowledged when a worker receives it; if the worker dies mid-task, the task is lost. With acks_late=True, it is acknowledged after completion; a crash causes redelivery, so duplicates are possible. Neither gives exactly-once. Design for at-least-once plus idempotency.

Idempotency techniques:

  • Natural keys: Payment.objects.get_or_create(external_id=...) backed by a unique constraint; the second run finds the row.
  • State checks: if invoice.status == "sent": return, updated atomically (update(status="sent") on status="queued" rows returns the number changed).
  • Lock or dedupe key: cache.add(f"task:{id}", 1, timeout) returns False when someone else holds it (the add is atomic on Redis/Memcached).
  • External APIs: pass an idempotency key to the provider.

Reliability settings:

  • Retries: autoretry_for=(TimeoutError,), retry_backoff=True, retry_jitter=True, max_retries=5. Do not retry non-transient errors (validation).
  • task_time_limit (hard kill) and task_soft_time_limit (raises SoftTimeLimitExceeded so you can clean up).
  • worker_prefetch_multiplier=1 with long tasks so a worker does not hoard messages.
  • task_acks_on_failure_or_timeout, broker_transport_options (visibility timeout on Redis must exceed the longest ETA or acks_late task, or tasks are redelivered while still running).
  • Result backend only when needed; set result_expires.

Operations:

  • Queues: task_routes = {"app.tasks.mail.*": {"queue": "mail"}} and dedicated worker pools, so a slow report cannot starve password-reset mail.
  • Enqueue after commit with transaction.on_commit; or use a transactional outbox for must-not-lose events.
  • Monitor queue length, task latency, failure and retry rates (Flower, Prometheus exporters), and alert on age of oldest message.
  • Pass IDs, keep payloads small, and version task signatures when changing arguments (old messages may still be in the queue).
  • Graceful shutdown: warm shutdown on deploy, so running tasks finish.
python
from celery import Celery, shared_task

app = Celery("demo")
app.conf.update(
    broker_url="memory://",
    task_always_eager=True,
    task_routes={"demo.mail.*": {"queue": "mail"}, "demo.reports.*": {"queue": "slow"}},
    worker_prefetch_multiplier=1,
)

PROCESSED = set()          # stands in for a database table with a unique constraint
SIDE_EFFECTS = []


@shared_task(name="demo.mail.send_receipt", bind=True, acks_late=True, autoretry_for=(TimeoutError,),
             retry_backoff=True, retry_jitter=True, max_retries=5, soft_time_limit=30, time_limit=45)
def send_receipt(self, payment_id):
    if payment_id in PROCESSED:                     # idempotency: a redelivered message becomes a no-op
        return "duplicate ignored"
    SIDE_EFFECTS.append(f"email for {payment_id}")
    PROCESSED.add(payment_id)
    return "sent"


print(send_receipt.delay(7).get(), "|", send_receipt.delay(7).get(), "| side effects:", SIDE_EFFECTS)
print("acks_late:", send_receipt.acks_late, "| max_retries:", send_receipt.max_retries,
      "| soft/hard limits:", send_receipt.soft_time_limit, send_receipt.time_limit)
print("backoff:", send_receipt.retry_backoff, "| jitter:", send_receipt.retry_jitter)

route = app.amqp.router.route({}, "demo.mail.send_receipt")
print("routed to queue:", route["queue"].name, "|", app.amqp.router.route({}, "demo.reports.monthly")["queue"].name)

Standalone script. Needs `pip install celery`. Eager mode with the in-memory broker stands in for a worker; the printed attributes are the settings a real worker would honour. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3, Celery 5.7.0): sent | duplicate ignored | side effects: ['email for 7'] acks_late: True | max_retries: 5 | soft/hard limits: 30 45 backoff: True | jitter: True routed to queue: mail | slow

Key points

  • At-least-once delivery means tasks must be idempotent
  • acks_late redelivers after crashes; duplicates become possible
  • Bounded retries with backoff and jitter; time limits
  • Separate queues and tuned prefetch prevent starvation
  • Monitor queue age; enqueue after commit or use an outbox

Common mistakes

  • Assuming exactly-once delivery
  • Setting acks_late without making tasks idempotent
  • Mixing slow and urgent tasks in one queue
  • Redis visibility timeout shorter than the longest task, causing duplicate runs
  • Changing task arguments without handling messages already queued

Follow-ups

  • How do you do exactly-once effects across a database and an external API?
  • What is the transactional outbox pattern?
  • How would you schedule periodic tasks safely with several beat instances?

Tips

  • State at-least-once clearly
  • Give two idempotency techniques
  • Name settings and queue separation
88.django-0088Hardsenior

How do you backfill or transform millions of rows in Django without locking the table or exhausting memory?

Process rows in primary-key ranges (for example 5,000 at a time), each in its own short transaction, using update() with expressions or bulk_update() on a chunk, and make the job resumable and idempotent. Avoid loading the whole table, avoid one giant transaction or ALTER with a default that rewrites the table, and run it as a management command or a non-atomic migration, throttled while watching replication lag and locks.

Full answer

Naive approach: for s in Student.objects.all(): s.slug = slugify(s.name); s.save(). On millions of rows it loads everything or keeps a server-side cursor open, issues one UPDATE per row and (in a migration) holds one transaction, locking rows, bloating WAL and delaying other writers.

Better:

  1. Add the new column as nullable (fast, metadata only), deploy code that writes both, then backfill, then add constraints. This is the expand and contract pattern.
  2. Iterate by key range, not OFFSET:
python
last_pk = 0
while True:
    ids = list(Student.objects.filter(pk__gt=last_pk, slug="").order_by("pk").values_list("pk", flat=True)[:BATCH])
    if not ids: break
    Student.objects.filter(pk__in=ids).update(slug=Lower("name"))      # or bulk_update for Python-computed values
    last_pk = ids[-1]
  1. Each batch commits separately: in a migration set atomic = False; in a management command, do not wrap the loop in atomic().
  2. Prefer a single SQL expression per batch (update(slug=Lower("name"))) over fetching rows. If Python must compute values, fetch only needed columns (only() or values_list), compute, then bulk_update(objs, ["slug"], batch_size=1000).
  3. Make it idempotent and resumable: filter on "not yet done" (slug="") so reruns only touch remaining rows, and log the last key.
  4. Throttle: time.sleep(0.1) between batches, or adapt to replication lag and lock waits. Run at off-peak times and set lock_timeout so the job fails fast rather than queueing behind long transactions.
  5. Verify with counts after, then add NOT NULL or constraints using the safe patterns (NOT VALID then VALIDATE on PostgreSQL, via RunSQL).

Do not run heavy data migrations in the deploy migration step if they take minutes; ship them as a separate command or background job. For read-only scans use .iterator(chunk_size=2000), which streams rows and (on PostgreSQL without pgbouncer in transaction pooling mode) uses server-side cursors.

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
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import time

from django.db import models, connection
from django.db.models.functions import Lower
from django.test.utils import CaptureQueriesContext


class Student(models.Model):
    name = models.CharField(max_length=40)
    slug = models.CharField(max_length=40, blank=True, default="")

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Student)

Student.objects.bulk_create([Student(name=f"Student {i:05d}") for i in range(1, 5001)], batch_size=1000)

BATCH = 1000


def backfill():
    last_pk, batches, updated = 0, 0, 0
    while True:
        ids = list(Student.objects.filter(pk__gt=last_pk, slug="").order_by("pk").values_list("pk", flat=True)[:BATCH])
        if not ids:
            return batches, updated
        updated += Student.objects.filter(pk__in=ids).update(slug=Lower("name"))   # one short statement per batch
        batches += 1
        last_pk = ids[-1]
        time.sleep(0)                                                              # throttle point (use a real pause in production)


with CaptureQueriesContext(connection) as ctx:
    print("first run (batches, rows):", backfill())
print("queries:", len(ctx), "(2 per batch plus the final empty check)")
print("second run is a no-op:", backfill())
print(Student.objects.filter(slug="").count(), Student.objects.get(pk=5000).slug)

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): first run (batches, rows): (5, 5000) queries: 11 (2 per batch plus the final empty check) second run is a no-op: (0, 0) 0 student 05000

Key points

  • Batch by primary-key ranges; each batch is its own short transaction
  • Prefer one SQL expression per batch over Python loops
  • Make the job idempotent and resumable with a not-done filter
  • Use atomic = False in migrations; throttle and watch locks and lag
  • Expand, backfill, then contract

Common mistakes

  • Looping over objects.all() and calling save() on each row
  • Running a long backfill inside one migration transaction
  • Using OFFSET pagination that gets slower on every batch
  • Making the job non-resumable so a crash means starting over
  • Adding NOT NULL or a default that rewrites the table before the backfill

Follow-ups

  • How would you add a NOT NULL constraint afterwards without a long lock?
  • How do you throttle based on replication lag?
  • Why is expand-and-contract safer than a single migration?

Tips

  • Describe key-range batching
  • Mention atomic = False
  • Say idempotent and resumable
89.django-0089Hardsenior

How do you read QuerySet.explain() output on PostgreSQL and choose indexes (B-tree, partial, composite, functional) based on the plan?

QuerySet.explain(analyze=True) runs EXPLAIN against the SQL Django generates. Look at the scan node (Seq Scan versus Index Scan or Bitmap Heap Scan), estimated versus actual rows, loops and time. Choose a B-tree index whose leading columns match equality filters then the sort, a partial index for a common subset, an expression index for functions like LOWER(), and always re-check the plan after creating it, with fresh statistics (ANALYZE).

Full answer

str(qs.query) shows SQL; qs.explain() shows how the database will execute it. explain(analyze=True) actually runs the query (do not use it on writes in production) and adds real timings.

What to read:

  • Scan type: Seq Scan reads the whole table. That is fine for tiny tables or when most rows are returned, and bad for selective filters on large tables. Index Scan, Index Only Scan and Bitmap Heap Scan use an index.
  • Rows: estimate versus actual. A large mismatch means stale statistics (run ANALYZE) or correlated columns.
  • Sort and filter nodes: Rows Removed by Filter shows wasted reads; a Sort node suggests an index could provide the order.
  • Time and loops: nested loops over many rows indicate N+1-like plans inside the query.

Index choices:

  • Composite (class_room_id, score): equality columns first, range or sort column last. It serves filter(class_room=x).order_by("score") and, with LIMIT, lets the database read the first rows in index order and skip the sort. When many rows match and no limit applies, the planner may still prefer a bitmap scan plus a sort, and that is a legitimate choice. A single-column index on class_room_id would always need the sort.
  • Partial index: Index(fields=["roll_no"], condition=Q(active=True), name=...) for queries that always filter active=True; smaller and faster to maintain.
  • Expression index: Index(Lower("email"), name=...) is used by email__iexact and annotate(Lower(...)) comparisons.
  • Covering include=[...] (PostgreSQL) allows index-only scans.
  • GinIndex/GistIndex for JSON, arrays, full text and trigram search.
  • Create indexes on busy tables with AddIndexConcurrently (non-atomic migration).

Costs: every index slows writes and uses space. Remove unused indexes (check pg_stat_user_indexes). Test on realistic row counts, because plans on small tables differ. The planner may legitimately ignore an index; do not force it, understand why.

python
import os
import sys
import types

import django
from django.conf import settings

sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

# Needs a running PostgreSQL server; connection details come from the usual PG* variables
settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ.get("PGDATABASE", "school"),
        "USER": os.environ.get("PGUSER", "postgres"),
        "PASSWORD": os.environ.get("PGPASSWORD", ""),
        "HOST": os.environ.get("PGHOST", "localhost"),
        "PORT": os.environ.get("PGPORT", "5432"),
    }},
)
django.setup()

from django.db import models, connection


class Fee(models.Model):
    class_room = models.IntegerField()
    score = models.IntegerField()
    active = models.BooleanField(default=True)

    class Meta:
        app_label = "school"


with connection.cursor() as cur:
    cur.execute("DROP TABLE IF EXISTS school_fee")
with connection.schema_editor() as editor:
    editor.create_model(Fee)

Fee.objects.bulk_create([Fee(class_room=i % 500, score=i % 97, active=(i % 50 == 0)) for i in range(60000)], batch_size=5000)


def plan(qs):
    return qs.explain()


def scan_kind(text):
    for kind in ("Index Only Scan", "Bitmap Heap Scan", "Index Scan", "Seq Scan"):   # check Bitmap first: "Bitmap Index Scan" contains "Index Scan"
        if kind in text:
            return kind


def analyze():
    with connection.cursor() as cur:
        cur.execute("ANALYZE school_fee")


query = Fee.objects.filter(class_room=42).order_by("score")
analyze()
print("without index:", scan_kind(plan(query)))

with connection.schema_editor() as editor:
    editor.add_index(Fee, models.Index(fields=["class_room", "score"], name="fee_room_score_idx"))
analyze()
text = plan(query)
print("composite index, all 120 matches:", scan_kind(text), "| sort node:", "Sort" in text)
text = plan(query[:5])
print("composite index, first 5 only:", scan_kind(text), "| sort node:", "Sort" in text)

partial = Fee.objects.filter(active=True, score=5)
with connection.schema_editor() as editor:
    editor.add_index(Fee, models.Index(fields=["score"], condition=models.Q(active=True), name="fee_active_score_idx"))
analyze()
print("partial index used:", "fee_active_score_idx" in plan(partial))
print("analyze shows actual time:", "actual time" in Fee.objects.filter(class_room=42).explain(analyze=True))

with connection.cursor() as cur:
    cur.execute("DROP TABLE school_fee")

Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): without index: Seq Scan composite index, all 120 matches: Bitmap Heap Scan | sort node: True composite index, first 5 only: Index Scan | sort node: False partial index used: True analyze shows actual time: True

Key points

  • explain() shows the plan; analyze=True runs it for real timings
  • Seq Scan versus Index Scan; compare estimated and actual rows
  • Composite index order: equality columns, then sort or range column
  • Partial and expression indexes match specific query shapes
  • Indexes cost writes; verify with ANALYZE and re-check plans

Common mistakes

  • Judging performance from SQL text alone without EXPLAIN
  • Running explain(analyze=True) on write statements in production
  • Putting the sort column before equality columns in a composite index
  • Adding indexes that are never used
  • Testing plans on tiny tables

Follow-ups

  • How do you create an index without blocking writes?
  • What does Index Only Scan need to work?
  • How would you find unused indexes?

Tips

  • Name scan types
  • Explain composite order
  • Mention ANALYZE and concurrent creation
90.django-0090Hardsenior

How do you implement full-text search and JSONField queries on PostgreSQL in Django using SearchVector, SearchQuery, SearchRank and GIN indexes?

django.contrib.postgres.search provides SearchVector, SearchQuery and SearchRank to run PostgreSQL full-text search with stemming and ranking, and a stored SearchVectorField with a GinIndex makes it fast. JSONField supports key lookups (data__grade), containment (data__contains) and key existence, and a GinIndex speeds containment queries. Choose a dedicated search engine when you need typo tolerance, facets or very large corpora.

Full answer

Basic search:

python
vector = SearchVector("title", weight="A") + SearchVector("body", weight="B")
query = SearchQuery("django migration", search_type="websearch")
Article.objects.annotate(search=vector, rank=SearchRank(vector, query)).filter(search=query).order_by("-rank")
  • SearchVector converts text to a tsvector with language-aware stemming (config="english"): "running" matches "run".
  • SearchQuery supports plain, phrase, raw and websearch (quotes, -exclusion, or), the friendliest for user input.
  • SearchRank scores matches; weights A to D bias title over body. Filter with the match operator (filter(search=query)), not rank__gt=0: PostgreSQL's ts_rank returns a tiny positive number (1e-20) for rows that do not match.
  • Computing the vector per query scans the table. For speed store it: a SearchVectorField kept in sync by a trigger, a GeneratedField (Django 5.0+), or updated in save(); then add GinIndex(fields=["search_vector"]), and filter with search_vector=query.
  • TrigramSimilarity (extension pg_trgm) handles typos and partial matches; needs TrigramExtension in a migration.

JSONField:

  • Profile.objects.filter(data__grade="A"), nested data__address__city="Pune", data__contains={"tags": ["math"]}, data__has_key="phone", data__score__gte=50 (cast to numeric by the lookup).
  • A GIN index on the JSON column accelerates contains, has_key and related operators; B-tree expression indexes help specific keys: Index(KeyTextTransform("grade", "data"), name=...).
  • Use JSON for sparse, schemaless attributes; keep fields you filter, join or constrain often as real columns.

Enabling: add django.contrib.postgres to INSTALLED_APPS and create extensions with CreateExtension operations in migrations. Remember that stemming depends on language configuration, and that search ranking is relevance in the linguistic sense, not business ranking.

python
import os
import sys
import types

import django
from django.conf import settings

sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

# Needs a running PostgreSQL server; connection details come from the usual PG* variables
settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.postgres", "school"],
    DATABASES={"default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ.get("PGDATABASE", "school"),
        "USER": os.environ.get("PGUSER", "postgres"),
        "PASSWORD": os.environ.get("PGPASSWORD", ""),
        "HOST": os.environ.get("PGHOST", "localhost"),
        "PORT": os.environ.get("PGPORT", "5432"),
    }},
)
django.setup()

from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.db import models, connection


class Article(models.Model):
    title = models.CharField(max_length=80)
    body = models.TextField()
    data = models.JSONField(default=dict)

    class Meta:
        app_label = "school"
        indexes = [GinIndex(fields=["data"], name="article_data_gin")]


with connection.cursor() as cur:
    cur.execute("DROP TABLE IF EXISTS school_article")
with connection.schema_editor() as editor:
    editor.create_model(Article)

Article.objects.create(title="Running Django migrations", body="How to run and squash migrations safely.", data={"level": "senior", "tags": ["django", "db"], "views": 120})
Article.objects.create(title="Intro to forms", body="Forms validate data. Migrations are not covered here.", data={"level": "fresher", "tags": ["django"], "views": 40})
Article.objects.create(title="FastAPI dependencies", body="Dependency injection with Depends.", data={"level": "mid", "tags": ["fastapi"], "views": 75})

vector = SearchVector("title", weight="A", config="english") + SearchVector("body", weight="B", config="english")
query = SearchQuery("migrating django", search_type="websearch", config="english")
hits = Article.objects.annotate(search=vector, rank=SearchRank(vector, query)).filter(search=query).order_by("-rank")
print("rank>0 would keep every row:", Article.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gt=0).count())
print([(a.title, round(a.rank, 3)) for a in hits])

print([a.title for a in Article.objects.filter(data__level="mid")])
print([a.title for a in Article.objects.filter(data__contains={"tags": ["django"]}).order_by("id")])
print([a.title for a in Article.objects.filter(data__views__gte=70).order_by("id")])
print(Article.objects.filter(data__has_key="level").count())

with connection.cursor() as cur:
    cur.execute("DROP TABLE school_article")

Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): rank>0 would keep every row: 3 [('Running Django migrations', 0.995)] ['FastAPI dependencies'] ['Running Django migrations', 'Intro to forms'] ['Running Django migrations', 'FastAPI dependencies'] 3

Key points

  • SearchVector, SearchQuery and SearchRank implement PostgreSQL full-text search
  • Store the vector and add a GinIndex for speed
  • websearch query type suits user input
  • JSONField supports key, contains and has_key lookups; GIN accelerates them
  • Use trigram similarity for typos; consider a search engine for big needs

Common mistakes

  • Computing a SearchVector on every request without storing and indexing it
  • Using raw search_type with user input and getting syntax errors
  • Forgetting django.contrib.postgres in INSTALLED_APPS
  • Storing frequently filtered fields only inside JSON
  • Expecting typo tolerance from plain full-text search

Follow-ups

  • How do you keep a stored search vector up to date?
  • How would trigram search differ?
  • When would you move to Elasticsearch or OpenSearch?

Tips

  • Explain stemming and rank
  • Mention GIN indexes
  • Know when JSON is the wrong choice
91.django-0091Hardsenior

How would you implement row-level multi-tenancy in Django so that a forgotten filter cannot leak one tenant's data to another?

Add a tenant foreign key to tenant-owned models, set the current tenant per request from the hostname or token in middleware (stored in a ContextVar), and make the default manager return only the current tenant's rows. Fail closed: if no tenant is set, raise an error rather than returning everything. Back it up with composite unique constraints including the tenant, database row-level security where available, and tests that try cross-tenant access.

Full answer

Models of multi-tenancy: separate database per tenant (strongest isolation, most operational work), schema per tenant on PostgreSQL (django-tenants), or a shared schema with a tenant_id column. The shared-schema model is simplest to operate and demands discipline so queries never forget the filter.

Design:

  1. Abstract base: class TenantOwned(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE); class Meta: abstract = True.
  2. Context: current_tenant = ContextVar("tenant", default=None). Middleware resolves the tenant (subdomain, header or token claim) and sets it for the request, and resets it afterwards. ContextVars work correctly with async views and threads, unlike module globals.
  3. Manager: get_queryset() returns super().get_queryset().filter(tenant=current_tenant.get()). If the tenant is None, raise NoTenantError, so a management command or background task that forgot to set a tenant fails loudly. Provide an explicit unscoped manager for admin and migrations, and name it clearly.
  4. Auto-assignment: save() sets tenant from context if empty, and rejects a mismatch.
  5. Constraints: uniqueness per tenant: UniqueConstraint(fields=["tenant", "roll_no"], name=...). Plain unique=True on roll_no would leak existence across tenants and block valid data.
  6. Related lookups: scoped managers do not automatically apply to related-object access or select_related joins, and Model.objects.get(pk=...) from untrusted IDs is scoped only if every model uses the scoped manager. Review foreign keys: a Mark must not point to another tenant's Student (validate in clean() or with composite foreign keys).
  7. Defence in depth: PostgreSQL row-level security with SET app.tenant_id per connection or transaction; caches and file paths prefixed with the tenant; tenant in log context; Celery tasks carry tenant_id and set the context.
  8. Tests: create two tenants, fetch with the wrong tenant context, expect not found; run a test that scans all models for the tenant field.

Beware of raw SQL, bulk_* helpers on unscoped managers, and aggregated reports in admin.

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
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from contextvars import ContextVar

from django.db import models, connection

current_tenant = ContextVar("tenant", default=None)


class NoTenantError(RuntimeError):
    pass


class TenantManager(models.Manager):
    def get_queryset(self):
        tenant = current_tenant.get()
        if tenant is None:
            raise NoTenantError("No tenant set: refusing to return unscoped data")
        return super().get_queryset().filter(tenant_id=tenant)


class Student(models.Model):
    tenant_id = models.IntegerField()
    roll_no = models.CharField(max_length=10)
    name = models.CharField(max_length=40)

    objects = TenantManager()
    unscoped = models.Manager()

    class Meta:
        app_label = "school"
        constraints = [models.UniqueConstraint(fields=["tenant_id", "roll_no"], name="uniq_roll_per_tenant")]

    def save(self, *args, **kwargs):
        tenant = current_tenant.get()
        if self.tenant_id is None and tenant is not None:
            self.tenant_id = tenant
        elif tenant is not None and self.tenant_id != tenant:
            raise NoTenantError("Cannot write another tenant's row")
        super().save(*args, **kwargs)


with connection.schema_editor() as editor:
    editor.create_model(Student)


def as_tenant(tenant_id):
    class Ctx:
        def __enter__(self):
            self.token = current_tenant.set(tenant_id)

        def __exit__(self, *exc):
            current_tenant.reset(self.token)
    return Ctx()


with as_tenant(1):
    Student(roll_no="A1", name="Asha").save()
with as_tenant(2):
    Student(roll_no="A1", name="Ravi").save()                 # same roll number is fine in another tenant
    Student(roll_no="B2", name="Kiran").save()

with as_tenant(1):
    print([s.name for s in Student.objects.all()])
with as_tenant(2):
    print([s.name for s in Student.objects.all()])
    print(Student.objects.filter(pk=1).exists(), "<- tenant 1's row id is invisible to tenant 2")

try:
    Student.objects.all()
except NoTenantError as exc:
    print("fail closed:", exc)

print(Student.unscoped.count(), "rows seen through the explicit unscoped manager")

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): ['Asha'] ['Ravi', 'Kiran'] False <- tenant 1's row id is invisible to tenant 2 fail closed: No tenant set: refusing to return unscoped data 3 rows seen through the explicit unscoped manager

Key points

  • Choose isolation level: database, schema or shared tables
  • Tenant from middleware in a ContextVar
  • Scoped default manager that fails closed
  • Uniqueness and foreign keys must include the tenant
  • Add database RLS and tests for cross-tenant access

Common mistakes

  • Relying on developers to remember .filter(tenant=...) in every query
  • Returning all rows when no tenant is set
  • Using plain unique=True on fields that should be unique per tenant
  • Storing the tenant in a module-level global
  • Forgetting tenant context in Celery tasks and management commands

Follow-ups

  • How does PostgreSQL row-level security complement this?
  • When would you choose schema-per-tenant?
  • How do you prevent foreign keys pointing across tenants?

Tips

  • Say fail closed
  • Describe the ContextVar and middleware
  • Mention per-tenant uniqueness
92.django-0092Hardsenior

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
93.django-0093Hardsenior

What is a cache stampede and how do you prevent it in Django using locks, TTL jitter and stale-while-revalidate?

A cache stampede (dogpile) happens when a popular key expires and many requests recompute it simultaneously, overloading the database. Prevent it with a short-lived lock using cache.add() (atomic on Redis and Memcached) so one request recomputes while others wait or serve stale data, add random jitter to TTLs so keys do not expire together, refresh early before expiry, and warm hot keys from a background job.

Full answer

Scenario: an expensive leaderboard query takes 2 seconds and is cached for 60 seconds. At expiry, 500 concurrent requests all miss the cache and run the query, saturating the database; some time out and retry, making it worse.

Techniques:

  1. Single flight with a lock: the first request that gets cache.add("lock:leaderboard", 1, timeout=10) (returns True only for one caller) computes and sets the value; others either wait briefly and re-read, or serve a stale copy. The lock needs its own timeout so a crashed worker does not block forever, and must be released (delete) after setting the value. cache.add is atomic on Redis and Memcached; LocMemCache is atomic only within one process.
  2. TTL jitter: timeout = base + random.randint(0, base // 10) so many keys written together do not expire together.
  3. Soft expiry (stale-while-revalidate): store (value, soft_expiry) with a long hard TTL. After the soft expiry, one caller refreshes (under the lock) while the rest keep serving the old value.
  4. Probabilistic early refresh: each request has a small chance of refreshing before the expiry, increasing as expiry nears.
  5. Warm the cache from a scheduled job and let requests only read.
  6. Reduce the cost: better query, precomputed tables, shorter work.

Other points: cache.get_or_set() does not prevent stampedes (several callers can compute at once). Negative caching (caching "not found" briefly) stops repeated misses on missing keys. Per-view cache_page has the same stampede behaviour at expiry. Redis-based locks from libraries (django-redis cache.lock) offer owned, auto-extending locks. Remember that cache invalidation on writes can trigger stampedes too, so prefer updating the value or refreshing in the background.

Measure: log cache misses and recompute counts; a spike of simultaneous recomputes of one key is the signature.

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
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import random
import threading
import time

from django.core.cache import cache

compute_count = {"naive": 0, "locked": 0}
counter_lock = threading.Lock()


def expensive(kind):
    with counter_lock:
        compute_count[kind] += 1
    time.sleep(0.3)                                       # a slow query
    return {"top": "Asha"}


def naive(key):
    value = cache.get(key)
    if value is None:
        value = expensive("naive")
        cache.set(key, value, 60)
    return value


def single_flight(key):
    value = cache.get(key)
    if value is not None:
        return value
    if cache.add(f"lock:{key}", 1, timeout=10):             # atomic: only one caller wins
        try:
            value = expensive("locked")
            cache.set(key, value, 60 + random.randint(0, 6))   # jittered TTL
        finally:
            cache.delete(f"lock:{key}")
        return value
    for _ in range(100):                                    # losers wait briefly and re-read
        time.sleep(0.02)
        value = cache.get(key)
        if value is not None:
            return value
    return expensive("locked")


def stampede(fn, key, n=8):
    start = threading.Barrier(n)
    results = []

    def worker():
        start.wait()
        results.append(fn(key))

    threads = [threading.Thread(target=worker) for _ in range(n)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return results


stampede(naive, "board:naive")
stampede(single_flight, "board:locked")
print("naive recomputations:", compute_count["naive"])
print("single-flight recomputations:", compute_count["locked"])
print(cache.add("lock:x", 1, timeout=5), cache.add("lock:x", 1, timeout=5))

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. LocMemCache is the default cache, so locks only coordinate threads inside this one process; use Redis or Memcached in production. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): naive recomputations: 8 single-flight recomputations: 1 True False

Key points

  • Stampede: many requests recompute an expired hot key
  • cache.add() as an atomic, expiring lock gives single-flight recompute
  • Jitter TTLs and use soft expiry with stale serving
  • get_or_set() does not prevent stampedes
  • Warm hot keys from background jobs

Common mistakes

  • Assuming get_or_set prevents duplicate computation
  • Using a lock without a timeout, so a crashed worker blocks everyone
  • Giving all keys the same TTL so they expire together
  • Using LocMemCache locks across several worker processes

Follow-ups

  • How does stale-while-revalidate work in practice?
  • What are the risks of a distributed lock?
  • How would you warm the cache on deploy?

Tips

  • Describe the stampede in one sentence
  • Give two prevention techniques
  • Note the lock timeout
94.django-0094Hardsenior

How do you stream a large export from Django with StreamingHttpResponse and iterator() without loading everything into memory?

StreamingHttpResponse takes an iterator of byte or string chunks and sends them as they are produced, so a large CSV can be written row by row while the database cursor is read with queryset.iterator(). Memory stays flat, the first bytes reach the client quickly, and the response has no Content-Length. Trade-offs: middleware that reads content breaks streaming, errors after the first chunk cannot change the status, and long-lived connections occupy workers.

Full answer

Naive exports build the whole file: HttpResponse with a csv.writer and every row in memory, or a list of 500,000 model objects. That risks memory exhaustion and request timeouts.

Streaming pattern:

python
class Echo:
    def write(self, value):
        return value                  # csv.writer calls write(); we return the line instead of storing it

def export(request):
    writer = csv.writer(Echo())
    def rows():
        yield writer.writerow(["roll_no", "name"])
        for s in Student.objects.values_list("roll_no", "name").iterator(chunk_size=2000):
            yield writer.writerow(s)
    response = StreamingHttpResponse(rows(), content_type="text/csv")
    response["Content-Disposition"] = 'attachment; filename="students.csv"'
    return response

Why each part matters:

  • values_list(...) skips model instance creation (cheaper); iterator(chunk_size=...) avoids caching the whole result in the QuerySet. On PostgreSQL it uses server-side cursors, unless connection pooling in transaction mode (pgbouncer) forbids them: then set DISABLE_SERVER_SIDE_CURSORS: True and Django fetches in chunks client-side.
  • response.streaming is True; response.streaming_content yields chunks. response.content raises an error.
  • Under ASGI, async iterators are supported, and Django warns when a sync iterator is used (it consumes it in a thread).
  • Middleware: GZipMiddleware and ConditionalGetMiddleware can buffer or skip streams. Content-Length is unknown, so clients show no progress bar.
  • Errors: if the query fails after the first chunk, the client receives a truncated file with status 200. Validate parameters first and consider a checksum or a final marker row.
  • Long exports tie up a worker; for very large or slow exports, generate the file in a background task, store it (object storage), and send a download link.
  • FileResponse is the tool for serving existing files, with range support.

Add authorisation and row limits, and never include unescaped formulas (=, +, @) from user data in CSVs opened in spreadsheets (CSV injection).

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 csv

from django.db import models, connection
from django.http import StreamingHttpResponse
from django.test import Client
from django.urls import path


class Student(models.Model):
    roll_no = models.CharField(max_length=10)
    name = models.CharField(max_length=40)

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Student)
Student.objects.bulk_create([Student(roll_no=f"R{i:04d}", name=f"Student {i}") for i in range(1, 2501)], batch_size=500)


class Echo:
    def write(self, value):
        return value


def export(request):
    writer = csv.writer(Echo())

    def rows():
        yield writer.writerow(["roll_no", "name"])
        for row in Student.objects.values_list("roll_no", "name").order_by("id").iterator(chunk_size=1000):
            yield writer.writerow(row)

    response = StreamingHttpResponse(rows(), content_type="text/csv")
    response["Content-Disposition"] = 'attachment; filename="students.csv"'
    return response


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

r = Client().get("/export/")
print(r.status_code, r.streaming, r["Content-Disposition"], "Content-Length" in r.headers)
chunks = list(r.streaming_content)
print(len(chunks), "chunks;", chunks[0], chunks[1], chunks[-1])
try:
    r.content
except AttributeError as exc:
    print("content:", exc)

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 True attachment; filename="students.csv" False 2501 chunks; b'roll_no,name\r\n' b'R0001,Student 1\r\n' b'R2500,Student 2500\r\n' content: This StreamingHttpResponse instance has no `content` attribute. Use `streaming_content` instead.

Key points

  • StreamingHttpResponse consumes an iterator and sends chunks as produced
  • iterator(chunk_size) and values_list keep memory flat
  • No Content-Length; errors after the first chunk cannot change the status
  • Mind middleware, pgbouncer cursors and worker occupancy
  • Offload very large exports to background jobs

Common mistakes

  • Building the whole CSV in memory
  • Iterating a normal QuerySet that caches every row
  • Expecting a correct status code if the failure happens mid-stream
  • Using server-side cursors behind transaction-pooling pgbouncer
  • Writing user data into CSV without neutralising formulas

Follow-ups

  • How does streaming behave under ASGI versus WSGI?
  • How would you resume or retry a failed export?
  • When is a background job better?

Tips

  • Show the Echo buffer trick
  • Mention iterator(chunk_size)
  • State the trade-offs
95.django-0095Hardsenior

How do you containerise a Django app for production: Dockerfile, Gunicorn, static files with WhiteNoise, migrations and health checks?

Build a slim multi-stage image that installs pinned dependencies, runs as a non-root user, collects static files at build time, and starts Gunicorn (or Uvicorn workers) with settings read from environment variables. WhiteNoise serves hashed, compressed static files directly from the app container so a CDN or proxy can cache them. Run migrations as a separate release step rather than on every container start, expose a health endpoint, and log to stdout.

Full answer

A reasonable image:

dockerfile
FROM python:3.13-slim AS build
ENV PIP_NO_CACHE_DIR=1 PYTHONDONTWRITEBYTECODE=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --prefix=/install -r requirements.txt

FROM python:3.13-slim
ENV PYTHONUNBUFFERED=1 DJANGO_SETTINGS_MODULE=proj.settings
RUN useradd --create-home app
WORKDIR /app
COPY --from=build /install /usr/local
COPY . .
RUN SECRET_KEY=build-only python manage.py collectstatic --noinput
USER app
EXPOSE 8000
CMD ["gunicorn", "proj.wsgi", "--bind", "0.0.0.0:8000", "--workers", "3", "--access-logfile", "-"]

Decisions:

  • Pin dependencies with hashes or a lock file, use a slim base image, no build tools in the final stage, and a non-root user.
  • Configuration comes from environment variables (SECRET_KEY, DATABASE_URL, ALLOWED_HOSTS, CSRF_TRUSTED_ORIGINS). Never bake secrets into the image; the collectstatic build step needs a dummy key only.
  • Static files: STORAGES["staticfiles"]["BACKEND"] = "whitenoise.storage.CompressedManifestStaticFilesStorage" gives content-hashed names (app.3f2a1b9c.css), gzip or Brotli copies and Cache-Control: max-age=315360000, public, immutable (ten years, safe because the name changes with the content). Add WhiteNoiseMiddleware right after SecurityMiddleware. Put a CDN in front for traffic. User uploads (media) belong in object storage, not the container filesystem.
  • Workers: Gunicorn --workers around 2 to 4 per CPU core for sync workers; for ASGI use gunicorn -k uvicorn.workers.UvicornWorker (or uvicorn --workers). Set --timeout, --max-requests with jitter to recycle leaky processes, and --graceful-timeout.
  • Reverse proxy: SECURE_PROXY_SSL_HEADER, USE_X_FORWARDED_HOST only if the proxy sets them, and --forwarded-allow-ips.
  • Migrations: run python manage.py migrate as a release job (init container or pipeline step) before the new version takes traffic; keep migrations backward-compatible so old and new pods can overlap.
  • Health: /healthz/ returns 200 without touching the database (liveness); readiness may check the database.
  • Logs to stdout in a structured format; one process per container.
python
import re
import sys
import tempfile
import types
from pathlib import Path

WORK = Path(tempfile.mkdtemp())
(WORK / "assets").mkdir()
(WORK / "assets" / "app.css").write_text("body { font-family: sans-serif; }\n" * 50)

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__,
    DEBUG=False,
    STATIC_URL="/static/",
    STATIC_ROOT=str(WORK / "staticfiles"),
    STATICFILES_DIRS=[str(WORK / "assets")],
    STORAGES={"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
              "staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"}},
    MIDDLEWARE=["django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware"],
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.staticfiles", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import io

from django.core.management import call_command
from django.http import HttpResponse
from django.templatetags.static import static
from django.test import Client
from django.urls import path


def healthz(request):
    return HttpResponse("ok")                         # liveness: no database access


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

call_command("collectstatic", interactive=False, verbosity=0)
names = sorted(p.name for p in (WORK / "staticfiles").iterdir())
mask = lambda name: re.sub(r"\.[0-9a-f]{12}\.", ".<hash>.", name)
print([mask(n) for n in names])

url = static("app.css")
print(mask(url))
c = Client()
r = c.get(url, headers={"Accept-Encoding": "gzip"})
print(r.status_code, r.headers.get("Content-Encoding"), r.headers.get("Cache-Control"))
print(c.get("/healthz/").content)

Standalone script. Needs `pip install whitenoise`. It builds a temporary static directory, runs collectstatic with the manifest storage and fetches a file through WhiteNoise. The Dockerfile and Gunicorn command are shown in the answer text, not executed here. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['app.<hash>.css', 'app.<hash>.css.gz', 'app.css', 'app.css.gz', 'staticfiles.json'] /static/app.<hash>.css 200 gzip max-age=315360000, public, immutable b'ok'

Key points

  • Multi-stage, slim, non-root image with pinned dependencies
  • Configuration through environment variables; no secrets in images
  • WhiteNoise serves hashed, compressed static files with long cache lifetimes
  • Run migrations as a separate release step
  • Gunicorn worker count, timeouts and recycling; health endpoints; stdout logs

Common mistakes

  • Running migrate automatically in every container at start-up
  • Baking secrets or .env files into the image
  • Serving media uploads from the container filesystem
  • Running as root in the container
  • Setting Gunicorn workers without considering memory and database connections

Follow-ups

  • How would you roll out a breaking migration with zero downtime?
  • How do you size Gunicorn workers and database connections together?
  • How do liveness and readiness probes differ?

Tips

  • Walk through the Dockerfile stages
  • Mention WhiteNoise and hashed names
  • Say migrations as a release step
96.django-0096Hardsenior

How does JWT authentication work in Django REST Framework with SimpleJWT: access and refresh tokens, expiry, rotation and the security trade-offs?

SimpleJWT issues a short-lived signed access token (sent in Authorization: Bearer) and a longer-lived refresh token used only to get new access tokens. JWTAuthentication verifies the signature and expiry without a database lookup for the token itself. Rotation issues a new refresh token on each refresh, and the blacklist app can revoke refresh tokens. Trade-offs: access tokens cannot be revoked before expiry, so keep lifetimes short and store tokens carefully.

Full answer

Flow:

  1. POST /api/token/ with credentials returns {"access": "...", "refresh": "..."} (TokenObtainPairView).
  2. The client sends Authorization: Bearer <access> on API calls. JWTAuthentication checks the signature (HS256 with SECRET_KEY by default, or RS256 with a key pair), the exp claim and the token type, then loads the user by the user_id claim.
  3. When the access token expires (default 5 minutes), the client calls POST /api/token/refresh/ with the refresh token (default 1 day) and receives a new access token.

Settings (SIMPLE_JWT): ACCESS_TOKEN_LIFETIME, REFRESH_TOKEN_LIFETIME, ROTATE_REFRESH_TOKENS (issue a new refresh token on refresh), BLACKLIST_AFTER_ROTATION (needs rest_framework_simplejwt.token_blacklist in INSTALLED_APPS and its tables), ALGORITHM, SIGNING_KEY, AUDIENCE, ISSUER, UPDATE_LAST_LOGIN.

Security trade-offs:

  • Statelessness: the server does not store access tokens, which scales well, but a stolen or issued token stays valid until expiry. Short lifetimes limit damage; the blacklist (a database table) revokes refresh tokens for logout and rotation reuse detection.
  • Storage on the client: localStorage is readable by any XSS; an HttpOnly, Secure, SameSite cookie is safer against XSS but needs CSRF protection. Single-page apps often keep access tokens in memory and the refresh token in an HttpOnly cookie.
  • Claims are signed, not encrypted: anyone can read them. Do not put secrets or private data inside.
  • Use HTTPS only; rotate signing keys (RS256 with kid and JWKS is common across services); validate iss and aud when several services share keys.
  • Permissions still come from the user record: a deactivated user fails authentication, since the user is loaded on each request (USER_AUTHENTICATION_RULE).
  • Compare with sessions: server-side sessions can be revoked instantly and suit browser apps on one domain; JWTs suit mobile clients and cross-service calls.
python
import sys
import types
from datetime import timedelta

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__,
    REST_FRAMEWORK={"DEFAULT_AUTHENTICATION_CLASSES": ["rest_framework_simplejwt.authentication.JWTAuthentication"]},
    SIMPLE_JWT={"ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
                "ROTATE_REFRESH_TOKENS": True},
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "rest_framework_simplejwt", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.contrib.auth import get_user_model
from django.db import connection
from django.urls import path
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.test import APIClient
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import AccessToken
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

User = get_user_model()
with connection.schema_editor() as editor:
    editor.create_model(User)
user = User.objects.create_user("asha", password="s3cret-pass")


class Me(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({"user": request.user.username})


urlpatterns = [
    path("api/token/", TokenObtainPairView.as_view()),
    path("api/token/refresh/", TokenRefreshView.as_view()),
    path("api/me/", Me.as_view()),
]

c = APIClient()
print(c.post("/api/token/", {"username": "asha", "password": "wrong"}, format="json").status_code)
tokens = c.post("/api/token/", {"username": "asha", "password": "s3cret-pass"}, format="json").json()
print(sorted(tokens))
print(c.get("/api/me/").status_code)

c.credentials(HTTP_AUTHORIZATION="Bearer " + tokens["access"])
print(c.get("/api/me/").json())
claims = AccessToken(tokens["access"])
print(sorted(k for k in claims.payload if k in ("token_type", "exp", "user_id")), claims["token_type"])

c.credentials(HTTP_AUTHORIZATION="Bearer " + tokens["access"][:-3] + "abc")      # tampered signature
print("tampered:", c.get("/api/me/").status_code)

expired = AccessToken.for_user(user)
expired.set_exp(lifetime=-timedelta(seconds=1))
c.credentials(HTTP_AUTHORIZATION="Bearer " + str(expired))
print("expired:", c.get("/api/me/").status_code)

c.credentials()
refreshed = c.post("/api/token/refresh/", {"refresh": tokens["refresh"]}, format="json").json()
print("refresh returns:", sorted(refreshed))
user.is_active = False
user.save()
c.credentials(HTTP_AUTHORIZATION="Bearer " + refreshed["access"])
print("deactivated user:", c.get("/api/me/").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. Requires `pip install djangorestframework djangorestframework-simplejwt`. Token strings are random and time-based, so the snippet prints only claim names and status codes. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3, djangorestframework-simplejwt 5.5.1): 401 ['access', 'refresh'] 401 {'user': 'asha'} ['exp', 'token_type', 'user_id'] access tampered: 401 expired: 401 refresh returns: ['access', 'refresh'] deactivated user: 401

Key points

  • Short-lived access token plus longer-lived refresh token
  • JWTAuthentication verifies signature and expiry, then loads the user
  • Rotation issues a new refresh token; blacklist revokes
  • Claims are readable; store tokens carefully; use HTTPS
  • Sessions revoke instantly; JWTs suit mobile and service-to-service

Common mistakes

  • Storing access tokens in localStorage on pages that can suffer XSS
  • Using long access-token lifetimes because refresh feels annoying
  • Putting sensitive data in claims
  • Assuming logout revokes an access token
  • Sharing the SECRET_KEY across services instead of using asymmetric keys

Follow-ups

  • How does refresh-token reuse detection work?
  • How would you implement logout with SimpleJWT?
  • When would you pick sessions instead of JWTs?

Tips

  • Describe both tokens and lifetimes
  • Name trade-offs of statelessness
  • Mention storage in browsers
97.django-0097Hardsenior

How do deadlocks happen with Django and PostgreSQL, and how do you prevent them with consistent lock ordering and retry them safely?

A deadlock occurs when two transactions each hold a lock the other needs; PostgreSQL detects it after deadlock_timeout, aborts one transaction with SQLSTATE 40P01, and Django surfaces it as OperationalError. Prevent deadlocks by always locking rows in a consistent order (for example ordered by primary key), keeping transactions short, and handle the remainder by retrying the whole transaction with backoff, only for safe, idempotent units of work.

Full answer

Classic case: a transfer between two wallets. Transaction 1 moves money from A to B (locks A, then B). Transaction 2 moves money from B to A (locks B, then A). Each waits for the other, so neither can proceed. PostgreSQL notices after deadlock_timeout (1 second by default), cancels one transaction and the other continues.

Prevention:

  1. Lock in a deterministic order: list(Wallet.objects.select_for_update().filter(pk__in=[a, b]).order_by("pk")) locks both rows in ID order, whichever direction the transfer goes. Both transactions then queue on the lower ID first, and no cycle can form.
  2. Keep transactions short: no network calls, emails or slow computation while holding locks.
  3. Touch tables in a consistent order across code paths.
  4. Use F() expressions for single-row atomic updates; they take one row lock briefly.
  5. Prefer select_for_update(skip_locked=True) for work queues and nowait=True to fail fast.

Retry:

  • Deadlocks (40P01) and serialization failures at SERIALIZABLE or REPEATABLE READ (40001) are transient. The right response is to roll back and run the entire transaction again from the start, not only the failed statement.
  • In Django, the error appears as django.db.OperationalError with the driver error in __cause__ (psycopg.errors.DeadlockDetected, .sqlstate). Retry the outermost atomic() block, never from inside a nested block. Use a few attempts with exponential backoff and jitter.
  • The unit of work must be idempotent or contain only database effects that roll back; do not retry code that has already sent an email.
  • Log retries and alert when they spike: frequent deadlocks mean an ordering problem.

Diagnosis: PostgreSQL logs the two statements involved; log_lock_waits and pg_locks show waiters.

python
import os
import sys
import types

import django
from django.conf import settings

sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

# Needs a running PostgreSQL server; connection details come from the usual PG* variables
settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ.get("PGDATABASE", "school"),
        "USER": os.environ.get("PGUSER", "postgres"),
        "PASSWORD": os.environ.get("PGPASSWORD", ""),
        "HOST": os.environ.get("PGHOST", "localhost"),
        "PORT": os.environ.get("PGPORT", "5432"),
    }},
)
django.setup()

import threading
import time

from django.db import models, connection, transaction, OperationalError


class Wallet(models.Model):
    balance = models.IntegerField()

    class Meta:
        app_label = "school"


with connection.cursor() as cur:
    cur.execute("DROP TABLE IF EXISTS school_wallet")
with connection.schema_editor() as editor:
    editor.create_model(Wallet)
a = Wallet.objects.create(balance=100).pk
b = Wallet.objects.create(balance=100).pk


def transfer(src, dst, amount, ordered, gate=None):
    with transaction.atomic():
        ids = sorted([src, dst]) if ordered else [src, dst]
        for pk in ids:                                    # lock the rows one by one
            Wallet.objects.select_for_update().get(pk=pk)
            if gate is not None and pk == ids[0]:
                gate.wait(timeout=5)                      # make both transactions hold their first lock
        Wallet.objects.filter(pk=src).update(balance=models.F("balance") - amount)
        Wallet.objects.filter(pk=dst).update(balance=models.F("balance") + amount)


def with_retry(fn, attempts=4):
    for attempt in range(attempts):
        try:
            return fn(attempt)
        except OperationalError as exc:
            sqlstate = getattr(exc.__cause__, "sqlstate", None)
            if sqlstate not in ("40P01", "40001") or attempt == attempts - 1:
                raise
            time.sleep(0.05 * 2 ** attempt)               # backoff (add jitter in production)


def run(ordered, retry):
    outcome = {"deadlocks": 0, "retries": 0, "ok": 0}
    gate = threading.Barrier(2)

    def worker(src, dst):
        try:
            def job(attempt):
                if attempt:
                    outcome["retries"] += 1
                return transfer(src, dst, 10, ordered, gate if attempt == 0 and not ordered else None)
            (with_retry if retry else (lambda f: f(0)))(job)
            outcome["ok"] += 1
        except OperationalError as exc:
            if getattr(exc.__cause__, "sqlstate", None) == "40P01":
                outcome["deadlocks"] += 1
        finally:
            connection.close()

    threads = [threading.Thread(target=worker, args=(a, b)), threading.Thread(target=worker, args=(b, a))]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return outcome


print("opposite order, no retry:", run(ordered=False, retry=False))
print("opposite order, with retry:", run(ordered=False, retry=True))
print("consistent order:", run(ordered=True, retry=False))
print("total balance preserved:", sum(Wallet.objects.values_list("balance", flat=True)))

with connection.cursor() as cur:
    cur.execute("DROP TABLE school_wallet")

Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. The demo forces a deadlock with a barrier; PostgreSQL takes about a second (deadlock_timeout) to detect it, so the snippet takes a few seconds. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): opposite order, no retry: {'deadlocks': 1, 'retries': 0, 'ok': 1} opposite order, with retry: {'deadlocks': 0, 'retries': 1, 'ok': 2} consistent order: {'deadlocks': 0, 'retries': 0, 'ok': 2} total balance preserved: 200

Key points

  • Deadlock is a cycle of lock waits; PostgreSQL aborts one transaction (40P01)
  • Lock rows in a consistent order, such as order_by('pk')
  • Keep transactions short and free of external calls
  • Retry the whole outer transaction with backoff for 40P01 and 40001
  • Make the retried unit idempotent; log retries

Common mistakes

  • Locking rows in different orders in different code paths
  • Retrying only the failed statement instead of the whole transaction
  • Retrying work that already has external side effects
  • Holding transactions open across network calls
  • Ignoring deadlock log lines that point to an ordering bug

Follow-ups

  • How does SERIALIZABLE isolation produce 40001 errors and how do you retry them?
  • What do skip_locked and nowait do?
  • How do you find which queries deadlocked?

Tips

  • Explain the cycle with two transfers
  • Give the ordering fix
  • Say retry the outermost transaction
98.django-0098Hardsenior

How do you extend the Django ORM with a custom lookup, a custom Transform and a custom model field?

A Lookup subclass defines how a filter operator renders to SQL (as_sql returns the SQL fragment and parameters) and is registered on a field class with register_lookup; a Transform wraps a column in a function and can be chained before other lookups; a custom Field customises conversion with from_db_value, to_python and get_prep_value. Together they let filter(score__abs__gt=5) or filter(name__ne='x') read naturally while the database does the work.

Full answer

Lookup:

python
@CharField.register_lookup
class NotEqual(Lookup):
    lookup_name = "ne"
    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        rhs, rhs_params = self.process_rhs(compiler, connection)
        return f"{lhs} <> {rhs}", [*lhs_params, *rhs_params]

Usage: Student.objects.filter(name__ne="Asha"). process_lhs and process_rhs produce SQL and parameters safely, so values are always bound parameters, never concatenated. Never format user values into the SQL string.

Transform:

python
@IntegerField.register_lookup
class Abs(Transform):
    lookup_name = "abs"
    function = "ABS"

filter(delta__abs__gt=5) becomes ABS(delta) > 5. Because a transform returns a field-like expression, it can be chained with other lookups and transforms. Set output_field when the result type differs from the input (for example Length returns an integer).

Custom field: subclass Field or an existing field and override:

  • db_type() or get_internal_type() (the column type),
  • get_prep_value() (Python to database),
  • from_db_value() (database to Python on loading),
  • to_python() (forms and deserialisation), formfield(), deconstruct() (so migrations can recreate the field).

Rules and cautions:

  • Registration applies to all fields of that class in the process; register in AppConfig.ready() or at import time of a module that is always loaded.
  • Keep SQL portable or branch with as_postgresql and as_sqlite methods.
  • Functional indexes (Index(Abs("delta"), ...)) pair with transforms for speed.
  • Think before building: many needs are met by Func expressions, annotate, or built-in lookups. Custom fields are worth it for real domain types (money, a range, an encrypted value) that appear on several models.
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
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection
from django.db.models import Lookup, Transform


@models.CharField.register_lookup
class NotEqual(Lookup):
    lookup_name = "ne"

    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        rhs, rhs_params = self.process_rhs(compiler, connection)
        return f"{lhs} <> {rhs}", [*lhs_params, *rhs_params]


@models.IntegerField.register_lookup
class Abs(Transform):
    lookup_name = "abs"
    function = "ABS"


class TagsField(models.TextField):
    """Stores a Python list as comma-separated text."""

    def from_db_value(self, value, expression, connection):
        return [] if not value else value.split(",")

    def to_python(self, value):
        return value if isinstance(value, list) else self.from_db_value(value, None, None)

    def get_prep_value(self, value):
        return ",".join(value) if value else ""


class Reading(models.Model):
    sensor = models.CharField(max_length=20)
    delta = models.IntegerField()
    tags = TagsField(blank=True)

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Reading)

Reading.objects.create(sensor="lab", delta=-8, tags=["temp", "room-1"])
Reading.objects.create(sensor="hall", delta=3, tags=[])
Reading.objects.create(sensor="gym", delta=12, tags=["humidity"])

print([r.sensor for r in Reading.objects.filter(sensor__ne="hall").order_by("id")])
print([r.sensor for r in Reading.objects.filter(delta__abs__gt=5).order_by("id")])
print(str(Reading.objects.filter(delta__abs__gt=5).query).split("WHERE")[1].strip())
print(Reading.objects.get(sensor="lab").tags, Reading.objects.get(sensor="hall").tags)
print(list(Reading.objects.annotate(size=Abs("delta")).order_by("-size").values_list("sensor", "size")))

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): ['lab', 'gym'] ['lab', 'gym'] ABS("school_reading"."delta") > 5 ['temp', 'room-1'] [] [('gym', 12), ('lab', 8), ('hall', 3)]

Key points

  • Lookup defines an operator; Transform wraps a column in a function
  • Use process_lhs and process_rhs so values stay parameterised
  • register_lookup attaches to a field class
  • Custom fields override prep, load and deconstruct methods
  • Prefer Func or annotations when a one-off is enough

Common mistakes

  • Formatting values into the SQL string and creating SQL injection
  • Forgetting output_field for transforms that change the type
  • Registering lookups in a module that is not always imported
  • Writing a custom field without deconstruct(), breaking migrations
  • Building a custom field where a Func or annotation would do

Follow-ups

  • How do you make a lookup database-specific?
  • How would you create an index for a transform?
  • What does from_db_value not run for?

Tips

  • Distinguish lookup, transform and field
  • Mention parameterised SQL
  • Mention deconstruct()
99.django-0099Hardsenior

How do you design soft deletion in Django with a default manager, a restore path and a partial unique constraint, and what are its limits?

Soft deletion marks rows with deleted_at instead of removing them. Use a default manager that hides deleted rows, an all_objects manager to see them, a queryset delete() that updates the marker, and a partial UniqueConstraint(condition=Q(deleted_at__isnull=True)) so deleted rows do not block re-using values such as an email. Limits: cascades, foreign keys, unique lookups, privacy requirements and table growth need explicit design.

Full answer

Why: undo, audit trails, and keeping references (old invoices pointing at a deleted student). Costs: every query must exclude deleted rows, uniqueness gets complicated and storage grows.

Building blocks:

python
class AliveQuerySet(models.QuerySet):
    def delete(self):                       # bulk soft delete
        return self.update(deleted_at=timezone.now())
    def alive(self): return self.filter(deleted_at__isnull=True)

class SoftDeleteModel(models.Model):
    deleted_at = models.DateTimeField(null=True, blank=True, db_index=True)
    objects = AliveManager()                 # default: hides deleted rows
    all_objects = models.Manager()           # includes deleted rows
    def delete(self, *a, **kw): self.deleted_at = timezone.now(); self.save(update_fields=["deleted_at"])
    def restore(self): self.deleted_at = None; self.save(update_fields=["deleted_at"])
    class Meta: abstract = True

Partial unique constraint: UniqueConstraint(fields=["roll_no"], condition=Q(deleted_at__isnull=True), name="uniq_alive_roll_no") enforces uniqueness among live rows only (supported by PostgreSQL and SQLite; MySQL needs another approach). Restoring a row whose value is now used by a live row violates the constraint, so restore code must handle IntegrityError.

Limits and decisions:

  • The first manager defined becomes _default_manager, used by related managers and the admin; Django's _base_manager (used for FK access and validation) is unfiltered by default, so mark.student still resolves to a deleted student.
  • Cascades: on_delete does nothing for soft deletes. Decide whether children are hidden too (a queryset filter through the relation, a post_save that cascades, or an explicit service).
  • bulk operations: QuerySet.update() bypasses save(), and raw SQL and joins ignore the manager.
  • Privacy laws (erasure requests) need real deletion or anonymisation; soft delete alone does not satisfy them.
  • Retention: purge old soft-deleted rows with a scheduled job.
  • Alternatives: an archive table, event sourcing, or database triggers.
  • Libraries such as django-safedelete package these patterns.
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
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import IntegrityError, connection, models
from django.utils import timezone


class AliveQuerySet(models.QuerySet):
    def delete(self):
        return self.update(deleted_at=timezone.now())


class AliveManager(models.Manager.from_queryset(AliveQuerySet)):
    def get_queryset(self):
        return super().get_queryset().filter(deleted_at__isnull=True)


class Student(models.Model):
    roll_no = models.CharField(max_length=10)
    name = models.CharField(max_length=40)
    deleted_at = models.DateTimeField(null=True, blank=True)

    objects = AliveManager()
    all_objects = models.Manager.from_queryset(AliveQuerySet)()

    class Meta:
        app_label = "school"
        constraints = [models.UniqueConstraint(fields=["roll_no"], condition=models.Q(deleted_at__isnull=True),
                                               name="uniq_alive_roll_no")]

    def delete(self, *args, **kwargs):
        self.deleted_at = timezone.now()
        self.save(update_fields=["deleted_at"])

    def restore(self):
        self.deleted_at = None
        self.save(update_fields=["deleted_at"])


with connection.schema_editor() as editor:
    editor.create_model(Student)

asha = Student.objects.create(roll_no="BCA-1", name="Asha")
ravi = Student.objects.create(roll_no="BCA-2", name="Ravi")
asha.delete()
print("alive:", [s.name for s in Student.objects.order_by("id")], "| all rows:", Student.all_objects.count())

Student.objects.filter(name="Ravi").delete()                      # queryset delete is soft too
print("alive after queryset delete:", Student.objects.count(), "| all rows:", Student.all_objects.count())

Student.objects.create(roll_no="BCA-1", name="Asha (re-enrolled)")   # allowed: the old row is deleted
try:
    asha.restore()                                                   # the roll number is in use again
except IntegrityError:
    print("restore blocked by the partial unique constraint")
try:
    Student.objects.create(roll_no="BCA-1", name="Duplicate")
except IntegrityError:
    print("duplicate live roll_no rejected")

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. Partial unique constraints work on SQLite and PostgreSQL; MySQL does not support conditional constraints. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): alive: ['Ravi'] | all rows: 2 alive after queryset delete: 0 | all rows: 2 restore blocked by the partial unique constraint duplicate live roll_no rejected

Key points

  • Hide deleted rows through the default manager; keep an all_objects manager
  • Override queryset delete() as well as instance delete()
  • Partial unique constraint scoped to live rows
  • Cascades, FK access and raw SQL need explicit handling
  • Soft delete does not meet erasure requirements

Common mistakes

  • Overriding instance delete() but not queryset delete()
  • Using a plain unique=True and blocking re-use of deleted values
  • Assuming foreign key access hides soft-deleted related rows
  • Treating soft delete as compliance with erasure requests
  • Forgetting a purge policy so tables grow forever

Follow-ups

  • How do you cascade soft deletes to related rows?
  • How does the admin interact with the default manager?
  • What are alternatives to soft delete?

Tips

  • Describe both managers
  • Explain the partial unique constraint
  • Mention cascades and privacy
100.django-0100Hardsenior

How do you implement optimistic locking in Django with a version field to prevent lost updates, and when do you choose it over select_for_update()?

Optimistic locking adds a version column. A writer reads the row with its version, and the update runs as UPDATE ... WHERE id = x AND version = v SET ..., version = version + 1. If zero rows change, someone else updated first, so the code raises a conflict (HTTP 409 or 412) or retries after reloading. It avoids holding locks while users edit, and fits forms and APIs where conflicts are rare; select_for_update() suits short, contended read-modify-write sections.

Full answer

The lost update problem: two staff members open the same student record, both edit, and the second save silently overwrites the first one's changes, because Django's save() writes all fields without checking whether the row changed.

Pessimistic locking (select_for_update()) holds a row lock inside a transaction; it works for short critical sections but cannot span a user's think time (a form open for minutes) and risks deadlocks.

Optimistic locking detects conflicts at write time:

python
updated = Student.objects.filter(pk=self.pk, version=self.version).update(
    name=self.name, version=F("version") + 1)
if not updated:
    raise StaleObjectError
self.version += 1

How to expose it:

  • Include version in the response (or use it as an ETag). The client sends it back in the update (If-Match: "7" or a body field).
  • On mismatch, answer 409 Conflict (or 412 Precondition Failed when using If-Match) with the current representation so the user can merge or retry.
  • In server-side flows, catch the conflict, reload the row, reapply the change and retry a bounded number of times (only when the change is a function of the new state, like incrementing a counter).

Details:

  • The version check and the update must be one statement; reading then comparing in Python reintroduces the race.
  • For counters, skip versions and use F("count") + 1, which is atomic.
  • Every write path must bump the version: save(), update(), bulk_update(). Centralise it in a model method or service. Libraries such as django-concurrency add VersionField and handle save() for you.
  • PostgreSQL's xmin or an updated_at timestamp can serve as the version, but timestamps risk precision ties.
  • Choose optimistic when conflicts are rare and edits are long-lived; choose select_for_update when conflicts are frequent or the work must be serialised (inventory, balances).
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
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import connection, models
from django.db.models import F


class StaleObjectError(Exception):
    pass


class Student(models.Model):
    name = models.CharField(max_length=40)
    grade = models.CharField(max_length=2)
    version = models.IntegerField(default=1)

    class Meta:
        app_label = "school"

    def save_if_current(self):
        updated = Student.objects.filter(pk=self.pk, version=self.version).update(
            name=self.name, grade=self.grade, version=F("version") + 1)
        if not updated:
            raise StaleObjectError(f"student {self.pk} changed since version {self.version}")
        self.version += 1


with connection.schema_editor() as editor:
    editor.create_model(Student)

Student.objects.create(name="Asha", grade="B")

teacher_a = Student.objects.get(pk=1)                     # both users open the same record
teacher_b = Student.objects.get(pk=1)

teacher_a.grade = "A"
teacher_a.save_if_current()
print("first save ok, version", teacher_a.version)

teacher_b.name = "Asha Rao"
try:
    teacher_b.save_if_current()
except StaleObjectError as exc:
    print("conflict:", exc)

# plain save() would have silently overwritten teacher_a's grade change:
naive = Student.objects.get(pk=1)
stale = Student(pk=1, name="Asha Rao", grade="B", version=1)
stale.save()
print("naive save wrote:", Student.objects.get(pk=1).grade, "(grade A was lost)")

def update_with_retry(pk, change, attempts=3):
    for _ in range(attempts):
        obj = Student.objects.get(pk=pk)
        change(obj)
        try:
            obj.save_if_current()
            return obj
        except StaleObjectError:
            continue
    raise StaleObjectError("too many conflicts")

fresh = update_with_retry(1, lambda s: setattr(s, "grade", "A+"))
print(fresh.grade, fresh.version)

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): first save ok, version 2 conflict: student 1 changed since version 1 naive save wrote: B (grade A was lost) A+ 2

Key points

  • Lost update: the second save overwrites the first without noticing
  • Version check and update happen in one statement
  • Zero rows updated means conflict: answer 409 or 412 or retry
  • Every write path must increment the version
  • Optimistic for long edits and rare conflicts; select_for_update for hot rows

Common mistakes

  • Using plain save() on shared records and losing concurrent edits
  • Reading the version and comparing it in Python before updating
  • Forgetting to bump the version in update() or bulk paths
  • Retrying blindly when the change does not depend on the latest state
  • Using optimistic locking for hot rows with constant conflicts

Follow-ups

  • How would you expose the version through ETag and If-Match in DRF?
  • When would you use select_for_update instead?
  • How does a database-generated xmin differ from a version column?

Tips

  • Describe the lost update
  • Show the single-statement check
  • Pick between optimistic and pessimistic