← Interview prep

Django interview questions

Models, ORM, auth, and Django web patterns.

100 questions · Page 4 of 5

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

Page 4 of 5

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

61.django-0061Easyfresher

How do you define choices on a Django field using TextChoices and IntegerChoices, and how do you display the label?

TextChoices and IntegerChoices are enumeration classes that define stored values and human labels together. Pass Class.choices to the field, compare with Class.VALUE in code, and call get_<field>_display() for the label. Django 5.0 also accepts a mapping or a callable for choices directly, and the database stores only the value.

Full answer

Hard-coded strings like "P" scattered in code are easy to mistype. Enumeration types give names:

python
class Status(models.TextChoices):
    PENDING = "P", "Pending"
    PAID = "D", "Paid"

class Fee(models.Model):
    status = models.CharField(max_length=1, choices=Status, default=Status.PENDING)
  • First tuple item is the stored value; second is the label shown in forms and admin.
  • Use Status.PAID in code (it is a str subclass, so it compares equal to "D"), Status.choices for the list of pairs, Status.values, Status.labels, and Status("D").label.
  • fee.get_status_display() returns "Paid".
  • IntegerChoices does the same for integer columns.
  • Omitting the label makes Django build one from the member name (PAID becomes "Paid").
  • Django 5.0 lets you pass the enum class itself (choices=Status) or a dict or callable; earlier versions need Status.choices.

Behaviour to remember:

  • choices restricts forms and full_clean(), but not the database or save(). A CheckConstraint with status__in=Status.values makes the database enforce it.
  • Adding or reordering choices produces a migration (choices are part of the field state), but it changes no SQL.
  • Filtering uses the stored value: Fee.objects.filter(status=Status.PAID).
  • Store stable values; labels can change or be translated with gettext_lazy.
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.utils.translation import gettext_lazy as _


class Status(models.TextChoices):
    PENDING = "P", _("Pending")
    PAID = "D", _("Paid")


class Grade(models.IntegerChoices):
    FAIL = 0, "Fail"
    PASS = 1, "Pass"


class Fee(models.Model):
    status = models.CharField(max_length=1, choices=Status, default=Status.PENDING)
    result = models.IntegerField(choices=Grade.choices, default=Grade.PASS)

    class Meta:
        app_label = "school"


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

fee = Fee.objects.create()
print(fee.status, fee.get_status_display(), fee.status == Status.PENDING)
fee.status = Status.PAID
fee.save()
print(Fee.objects.filter(status=Status.PAID).count(), Status.choices, Status.values)
print(Status("D").label, Status.PAID.name, Grade.FAIL.value)
print(Fee._meta.get_field("status").choices)

fee.status = "X"
fee.save()                                                    # the database accepts it
try:
    fee.full_clean()
except Exception as exc:
    print("validation:", exc.message_dict)

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. Passing the enum class straight to choices needs Django 5.0 or later; use Status.choices on older versions. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): P Pending True 1 [('P', 'Pending'), ('D', 'Paid')] ['P', 'D'] Paid PAID 0 [('P', 'Pending'), ('D', 'Paid')] validation: {'status': ["Value 'X' is not a valid choice."]}

Key points

  • Enumeration classes give names to stored values
  • Class.choices feeds the field; Django 5.0 also accepts the class
  • get_FOO_display() returns the label
  • choices are not enforced by the database without a CheckConstraint
  • Keep stored values stable; translate labels only

Common mistakes

  • Comparing against literal strings instead of enum members
  • Assuming choices are enforced by the database
  • Using display labels in filters or APIs
  • Changing stored values when only the label should change

Follow-ups

  • How do you translate labels?
  • How would you add a database check for the allowed values?
  • What changed in Django 5.0 for choices?

Tips

  • Describe value vs label
  • Show get_FOO_display
  • Say that save() does not validate choices
62.django-0062Easyfresher

What is the difference between a plain Django view and a DRF @api_view or APIView, and what does Response give you?

DRF wraps Django views with request parsing (request.data for JSON, forms and files), content negotiation, a Response class that renders to JSON or other formats, authentication, permissions, throttling and consistent error handling. Use @api_view for small function endpoints and APIView for class-based ones, and move to generic views or viewsets for CRUD.

Full answer

A plain Django view receives an HttpRequest and must parse JSON, validate, serialise and set status codes by hand. DRF adds:

  • Request: request.data (parsed body for JSON, form data or multipart, always one place), request.query_params, request.user, request.auth.
  • Response(data, status=...): holds Python data and renders it later according to the client's Accept header (JSON by default, browsable API for browsers).
  • Policy classes: authentication_classes, permission_classes, throttle_classes, and parsers and renderers, configured globally in REST_FRAMEWORK or per view.
  • Exceptions: ValidationError, NotFound, PermissionDenied are turned into 400, 404 and 403 responses with a JSON body.

Function style:

python
@api_view(["GET", "POST"])
def hello(request):
    ...

Class style: class StudentList(APIView): def get(self, request): .... The method name selects the handler; unsupported methods return 405 automatically.

Normally the view uses a serializer to validate request.data and to build the response data. The levels of abstraction, from low to high: APIView, generic views (ListCreateAPIView), then ModelViewSet with a router.

Return Response(serializer.data, status=status.HTTP_201_CREATED) for created resources and let serializer.is_valid(raise_exception=True) produce the 400 response.

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

from rest_framework import serializers, status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.test import APIRequestFactory
from rest_framework.views import APIView

STUDENTS = [{"id": 1, "name": "Asha"}]


class StudentIn(serializers.Serializer):
    name = serializers.CharField(max_length=20)


class StudentList(APIView):
    def get(self, request):
        return Response(STUDENTS)

    def post(self, request):
        s = StudentIn(data=request.data)
        s.is_valid(raise_exception=True)            # becomes a 400 response with JSON errors
        STUDENTS.append({"id": len(STUDENTS) + 1, **s.validated_data})
        return Response(STUDENTS[-1], status=status.HTTP_201_CREATED)


@api_view(["GET"])
def ping(request):
    return Response({"pong": True, "params": dict(request.query_params)})


rf = APIRequestFactory()
view = StudentList.as_view()
r = view(rf.get("/students/"))
print(r.status_code, r.data)
r = view(rf.post("/students/", {"name": "Ravi"}, format="json"))
print(r.status_code, r.data)
r = view(rf.post("/students/", {"name": ""}, format="json"))
print(r.status_code, r.data)
print(view(rf.delete("/students/")).status_code)
print(ping(rf.get("/ping/?x=1")).data)

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): 200 [{'id': 1, 'name': 'Asha'}] 201 {'id': 2, 'name': 'Ravi'} 400 {'name': [ErrorDetail(string='This field may not be blank.', code='blank')]} 405 {'pong': True, 'params': {'x': ['1']}}

Key points

  • request.data parses JSON, form and multipart in one place
  • Response renders to the format the client asks for
  • @api_view or APIView add auth, permissions, throttling and errors
  • Unsupported methods return 405 automatically
  • Generic views and viewsets sit above APIView

Common mistakes

  • Parsing request.body by hand inside DRF views
  • Returning raw dictionaries with HttpResponse instead of Response
  • Skipping serializer validation and trusting request.data
  • Forgetting that the project-wide default permission is AllowAny

Follow-ups

  • What are the default authentication and permission classes?
  • When should you use a ViewSet instead of APIView?
  • How does content negotiation pick the renderer?

Tips

  • Mention request.data and Response
  • List what DRF adds automatically
  • Show the abstraction ladder
63.django-0063Easyfresher

How do you write a custom template filter or tag in Django, and what is a context processor?

A custom filter or tag is a Python function registered on a template.Library() in a templatetags module and loaded with {% load name %}. A context processor is a function that receives the request and returns a dict that is added to the context of every template rendered with a RequestContext, such as site name or the current user's unread count.

Full answer

Filters transform a value: {{ score|percent }}. Register with @register.filter. Simple tags compute values with arguments: {% grade_label score as label %} using @register.simple_tag. Inclusion tags render a small template with their own context. Mark output safe only when you built it with format_html(); never mark user input safe.

Layout: school/templatetags/school_tags.py (the folder needs the app in INSTALLED_APPS; restart the dev server after adding it). In the template: {% load school_tags %}.

Context processors are plain functions:

python
def site_info(request):
    return {"SITE_NAME": "Schoolabe"}

Add the dotted path to TEMPLATES[0]["OPTIONS"]["context_processors"]. They run on every render that has a request, so keep them cheap and never put database queries there without caching. Built-in ones add request, user, perms and messages.

When to use which:

  • Formatting a value: filter.
  • Computing something with several inputs, or need the context: simple tag.
  • Data every page needs: context processor (or pass it from the view for page-specific data).
  • Logic-heavy work belongs in views or model methods, not in tags.

Templates should stay presentation-only. If a tag is doing queries, move that to the view and pass the result.

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
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": False,
                "OPTIONS": {"libraries": {"school_tags": "__main__"},
                            "context_processors": ["django.template.context_processors.request", "__main__.site_info"]}}],
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django import template
from django.template import engines
from django.test import RequestFactory
from django.utils.html import format_html

register = template.Library()


@register.filter
def percent(value, total):
    return f"{100 * value / total:.0f}%"


@register.simple_tag
def badge(label):
    return format_html('<span class="badge">{}</span>', label)


def site_info(request):
    return {"SITE_NAME": "Schoolabe", "path": request.path}


tpl = engines["django"].from_string(
    "{% load school_tags %}{{ SITE_NAME }} {{ path }}: {{ score|percent:total }} {% badge name %}"
)
request = RequestFactory().get("/results/")
print(tpl.render({"score": 45, "total": 60, "name": "<Asha>"}, request))
print(engines["django"].from_string("{{ SITE_NAME|default:'no processor' }}").render({}))

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 tag library is registered from this file with OPTIONS libraries; in a project it lives in app/templatetags/. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): Schoolabe /results/: 75% <span class="badge">&lt;Asha&gt;</span> no processor

Key points

  • Filters transform values; tags can take several arguments
  • Libraries live in an app's templatetags package and are loaded with {% load %}
  • Use format_html and avoid mark_safe on user input
  • Context processors add variables to every template rendered with a request
  • Keep context processors cheap

Common mistakes

  • Marking user-supplied text safe with mark_safe
  • Running database queries in a context processor on every request
  • Forgetting to restart runserver after creating templatetags
  • Putting business logic into template tags

Follow-ups

  • How does autoescaping interact with simple_tag output?
  • How do inclusion tags differ from simple tags?
  • How would you cache a context processor result?

Tips

  • State where the module lives
  • Mention format_html
  • Warn about processor cost
64.django-0064Easyfresher

How does Django store passwords, and how do make_password(), check_password() and the password validators work?

Django never stores plain passwords. It stores an encoded string algorithm$iterations$salt$hash, created by make_password() or user.set_password(). check_password() hashes the candidate with the stored salt and compares in constant time. The hasher list in PASSWORD_HASHERS lets old hashes be upgraded transparently on login, and AUTH_PASSWORD_VALIDATORS enforce password quality.

Full answer

A password hash must be slow, salted and one-way. Django's default hasher is PBKDF2 with SHA-256 and a high iteration count, increased in each release. Argon2 and bcrypt are available as options after installing their libraries (pip install "django[argon2]"), and the first hasher in PASSWORD_HASHERS is used for new passwords.

The stored value looks like pbkdf2_sha256$1000000$salt$hash. Because the algorithm and iteration count are inside the string, Django can verify old hashes. When a user logs in and the stored hash uses an older hasher or fewer iterations, check_password() re-hashes and saves the updated value, so hardening happens gradually without a migration.

API:

  • make_password("secret") returns an encoded string. make_password(None) returns an unusable password (never matches).
  • check_password(raw, encoded) returns a boolean.
  • user.set_password(raw) hashes but does not save; call user.save(). User.objects.create_user() hashes for you; User.objects.create(password="x") stores raw text by mistake.
  • user.has_usable_password().

Validators in AUTH_PASSWORD_VALIDATORS: UserAttributeSimilarityValidator, MinimumLengthValidator, CommonPasswordValidator, NumericPasswordValidator. They run in forms (UserCreationForm, change-password), not on set_password(); call validate_password(raw, user) yourself in custom code.

Never log passwords, never email them, and never write your own hashing with hashlib.sha256.

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

from django.contrib.auth.hashers import check_password, identify_hasher, make_password
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError

encoded = make_password("correct horse battery")
algo, iterations, salt, digest = encoded.split("$")
print(algo, iterations.isdigit(), len(salt) > 0)
print(identify_hasher(encoded).algorithm)
print(check_password("correct horse battery", encoded), check_password("wrong", encoded))
print(make_password("correct horse battery") == encoded)           # new random salt each time

unusable = make_password(None)
print(check_password("anything", unusable), unusable.startswith("!"))

for candidate in ("short", "password123", "a-long-unique-passphrase-42"):
    try:
        validate_password(candidate)
        print(candidate, "-> ok")
    except ValidationError as exc:
        print(candidate, "->", exc.messages)

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): pbkdf2_sha256 True True pbkdf2_sha256 True False False False True short -> ['This password is too short. It must contain at least 10 characters.'] password123 -> ['This password is too common.'] a-long-unique-passphrase-42 -> ok

Key points

  • Stored value is algorithm$iterations$salt$hash
  • First entry in PASSWORD_HASHERS is used for new passwords
  • check_password upgrades old hashes on successful login
  • set_password does not save; create_user hashes
  • Validators run in forms or via validate_password

Common mistakes

  • Storing raw text with objects.create(password=...)
  • Using hashlib.sha256 for passwords
  • Forgetting user.save() after set_password()
  • Assuming validators run inside set_password()

Follow-ups

  • How do you migrate users from MD5 hashes to PBKDF2 safely?
  • What does the salt protect against?
  • Why is a high iteration count useful?

Tips

  • Show the hash format
  • Explain gradual upgrades
  • Name the validators
65.django-0065Easyfresher

How should Django settings differ between development and production, and how do you read secrets from environment variables?

Keep one codebase and vary configuration through environment variables (twelve-factor style) or small per-environment settings modules. Secrets such as SECRET_KEY and database passwords never go into git. Read them with os.environ, parse booleans and lists explicitly, fail fast when a required value is missing, and set DEBUG=False in production.

Full answer

Settings that change per environment: DEBUG, ALLOWED_HOSTS, SECRET_KEY, DATABASES, cache and email backends, CSRF_TRUSTED_ORIGINS, logging, security flags.

Pattern 1, environment variables with defaults only for safe values:

python
import os
DEBUG = os.environ.get("DJANGO_DEBUG", "0") == "1"
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]          # KeyError if missing: fail fast
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")

Convert types yourself: environment values are always strings, so "False" is truthy unless compared. Libraries such as django-environ or pydantic-settings add parsing, .env files for local use and database URL support.

Pattern 2, modules: settings/base.py, settings/dev.py (imports base, overrides), settings/prod.py, selected with DJANGO_SETTINGS_MODULE. Easy to read, but the prod file is still configured from the environment for secrets.

Rules:

  • A dev-only default for SECRET_KEY is acceptable; production must not start without a real one.
  • .env files are for local development, ignored by git, and never shipped in images.
  • Never set DEBUG=True in production: it leaks settings and tracebacks and keeps all SQL in memory.
  • Run python manage.py check --deploy against the production settings.
  • Empty string ALLOWED_HOSTS.split(",") gives [""]; filter out blanks.
  • Rotate secrets by supporting SECRET_KEY_FALLBACKS (Django 4.1+).
python
import os

os.environ.update({"DJANGO_DEBUG": "False", "DJANGO_SECRET_KEY": "k" * 60,
                   "DJANGO_ALLOWED_HOSTS": "schoolabe.com, www.schoolabe.com,", "DATABASE_PATH": ":memory:"})


def env_bool(name, default=False):
    raw = os.environ.get(name)
    return default if raw is None else raw.strip().lower() in {"1", "true", "yes", "on"}


def env_list(name):
    return [item.strip() for item in os.environ.get(name, "").split(",") if item.strip()]


def require(name):
    try:
        return os.environ[name]
    except KeyError:
        raise RuntimeError(f"Missing required environment variable {name}") from None


import django
from django.conf import settings

settings.configure(
    DEBUG=env_bool("DJANGO_DEBUG"),
    SECRET_KEY=require("DJANGO_SECRET_KEY"),
    ALLOWED_HOSTS=env_list("DJANGO_ALLOWED_HOSTS"),
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": os.environ["DATABASE_PATH"]}},
)
django.setup()

print(settings.DEBUG, settings.ALLOWED_HOSTS)
print(bool(os.environ["DJANGO_DEBUG"]), "<- a non-empty string is truthy, so parse it")
print(len(settings.SECRET_KEY))

del os.environ["DJANGO_SECRET_KEY"]
try:
    require("DJANGO_SECRET_KEY")
except RuntimeError as exc:
    print(exc)

Standalone script. It sets the variables itself so it runs anywhere; in production they come from the process environment or a secret manager. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): False ['schoolabe.com', 'www.schoolabe.com'] True <- a non-empty string is truthy, so parse it 60 Missing required environment variable DJANGO_SECRET_KEY

Key points

  • Environment variables are strings; parse them explicitly
  • Fail fast on missing secrets
  • Never commit secrets or .env files
  • check --deploy against production settings
  • SECRET_KEY_FALLBACKS supports key rotation

Common mistakes

  • Using bool(os.environ['DEBUG']) and getting True for 'False'
  • Committing .env or a real SECRET_KEY
  • Leaving DEBUG=True in production
  • Giving ALLOWED_HOSTS a blank entry from an empty variable

Follow-ups

  • How would you rotate SECRET_KEY without logging everyone out?
  • How do you keep secrets out of Docker images?
  • When is a settings package better than environment variables?

Tips

  • Mention fail-fast on missing secrets
  • Call out string-to-bool parsing
  • Name check --deploy
66.django-0066Easyfresher

How do you configure logging in Django with the LOGGING setting, and which loggers does Django itself use?

Django uses Python's logging module and applies the LOGGING dictionary (dictConfig format) at startup. A configuration names formatters, handlers (where records go), and loggers (which code emits them, with levels). Django emits to loggers such as django.request (4xx and 5xx), django.db.backends (SQL, DEBUG only) and django.security, and your code should use logging.getLogger(__name__).

Full answer

Four ideas: logger (named source), level (DEBUG, INFO, WARNING, ERROR, CRITICAL), handler (destination: console, file, email, external service) and formatter (layout).

python
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {"plain": {"format": "{levelname} {name} {message}", "style": "{"}},
    "handlers": {"console": {"class": "logging.StreamHandler", "formatter": "plain"}},
    "loggers": {"school": {"handlers": ["console"], "level": "INFO"}},
    "root": {"handlers": ["console"], "level": "WARNING"},
}

Key points:

  • Always "version": 1 and, normally, "disable_existing_loggers": False (otherwise libraries' loggers go silent).
  • In modules: logger = logging.getLogger(__name__) and logger.info("Fee paid", extra=...). Use lazy formatting (logger.info("paid %s", amount)), and logger.exception("...") inside except to include the traceback.
  • Django loggers: django (parent), django.request (a warning for 4xx, an error for 5xx), django.server (runserver lines), django.template, django.db.backends (every query at DEBUG, only when DEBUG=True), django.security.*.
  • By default Django sends error logs to admins by email with AdminEmailHandler only when DEBUG=False, and to the console when DEBUG=True.
  • In containers write to stdout and let the platform collect it; use structured (JSON) formatters for searching.
  • Never log passwords, tokens or full personal records.
  • Set levels by environment through the settings, e.g. os.environ.get("LOG_LEVEL", "INFO").
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__,
    LOGGING={
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {"plain": {"format": "{levelname} {name}: {message}", "style": "{"}},
        "handlers": {"console": {"class": "logging.StreamHandler", "stream": "ext://sys.stdout", "formatter": "plain"}},
        "loggers": {"school": {"handlers": ["console"], "level": "INFO"},
                    "django.request": {"handlers": ["console"], "level": "WARNING", "propagate": False}},
    },
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import logging

from django.http import HttpResponse
from django.test import Client
from django.urls import path

logger = logging.getLogger("school.fees")


def pay(request):
    logger.info("Fee received for %s", request.GET.get("roll_no"))
    logger.debug("this DEBUG line is below the INFO threshold")
    try:
        1 / 0
    except ZeroDivisionError:
        logger.warning("Could not compute late fee", exc_info=False)
    return HttpResponse("ok")


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

c = Client()
c.get("/pay/?roll_no=BCA-17")
c.get("/missing/")                                       # django.request logs the 404 as a warning

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): INFO school.fees: Fee received for BCA-17 WARNING school.fees: Could not compute late fee WARNING django.request: Not Found: /missing/

Key points

  • LOGGING is dictConfig: formatters, handlers, loggers
  • Use getLogger(__name__) in your modules
  • disable_existing_loggers should normally be False
  • django.request logs 4xx and 5xx responses
  • Log to stdout in containers; never log secrets

Common mistakes

  • Leaving disable_existing_loggers at its default of True
  • Using print() instead of logging in server code
  • Formatting messages with f-strings that run even when the level is disabled
  • Logging secrets, tokens or full request bodies

Follow-ups

  • How do you add a request ID to every log line?
  • How do you send errors to Sentry or a similar tool?
  • What does django.db.backends log, and when?

Tips

  • Define logger, handler, formatter
  • Name the Django loggers
  • Mention stdout in containers
67.django-0067Easyfresher

What are the most useful manage.py commands in Django, and how do dumpdata, loaddata, check and showmigrations work?

manage.py (or django-admin) runs management commands. Daily ones are runserver, makemigrations, migrate, createsuperuser, shell, test, collectstatic and check. dumpdata and loaddata export and import fixtures as JSON, showmigrations lists which migrations are applied, and check runs the system check framework to catch configuration problems early.

Full answer

Common commands:

  • runserver: development server with autoreload. Never use it in production.
  • makemigrations [app] and migrate [app] [name]: create and apply schema changes. sqlmigrate app 0003 prints the SQL; showmigrations lists applied ([X]) and unapplied ([ ]) migrations; makemigrations --check --dry-run fails in CI if model changes lack a migration.
  • createsuperuser, changepassword.
  • shell: a Python REPL with Django configured (shell -c "..." for one-liners).
  • check: runs system checks; check --deploy adds production checks.
  • test: runs the test suite; --parallel and --keepdb speed it up.
  • collectstatic: gathers static files into STATIC_ROOT for deployment.
  • dumpdata app.Model --indent 2 writes JSON fixtures; loaddata file.json loads them (objects with the same primary key are overwritten). dumpdata --natural-foreign avoids hard-coded foreign key IDs for content types. Fixtures suit small seed data and tests, not full backups; use database tools for backups.
  • dbshell: opens the database's own client. inspectdb generates models from an existing database. flush empties all tables. diffsettings shows settings that differ from defaults.
  • startapp, startproject: scaffolding.

python manage.py help <command> shows options. You can also write your own commands in management/commands/ and call any command from Python with call_command("check"), which is how tests and scripts reuse them.

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 io

from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core import checks
from django.core.management import call_command, get_commands
from django.db import connection

with connection.schema_editor() as editor:
    for model in (ContentType, Permission, Group):
        editor.create_model(model)

call_command("check")                       # raises SystemCheckError if a check fails
print("check problems:", checks.run_checks())

Group.objects.create(name="Teachers")
Group.objects.create(name="Students")
dump = io.StringIO()
call_command("dumpdata", "auth.group", stdout=dump)
print(dump.getvalue())

Group.objects.filter(name="Students").update(name="Changed locally")
with open("groups.json", "w") as f:
    f.write(dump.getvalue())
call_command("loaddata", "groups.json", verbosity=0)          # same primary keys are overwritten
print(sorted(g.name for g in Group.objects.all()))

known = get_commands()
print([c for c in ("runserver", "makemigrations", "migrate", "shell", "dumpdata", "loaddata", "check", "collectstatic") if c in known])

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 snippet uses the built-in auth.group model because dumpdata skips apps without a models module, and it writes groups.json in the current folder. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): System check identified no issues (0 silenced). check problems: [] [{"model": "auth.group", "pk": 1, "fields": {"name": "Teachers", "permissions": []}}, {"model": "auth.group", "pk": 2, "fields": {"name": "Students", "permissions": []}}] ['Students', 'Teachers'] ['runserver', 'makemigrations', 'migrate', 'shell', 'dumpdata', 'loaddata', 'check']

Key points

  • makemigrations writes files; migrate applies them
  • check and check --deploy catch problems early
  • dumpdata and loaddata move small JSON fixtures
  • showmigrations and sqlmigrate show state and SQL
  • call_command runs commands from Python

Common mistakes

  • Using runserver in production
  • Treating dumpdata fixtures as database backups
  • Skipping makemigrations --check in CI
  • Loading fixtures that hard-code content type IDs

Follow-ups

  • How do you write a custom management command?
  • What does migrate --fake do and when is it risky?
  • How do you run a command from a test?

Tips

  • List commands by purpose
  • Mention the CI check
  • Name call_command
68.django-0068Mediummid

How do you compute several grouped statistics in one Django query using Count, Sum and Avg with the filter argument and values().annotate()?

Call values("field") to choose the GROUP BY column, then annotate() with aggregate functions. Each aggregate accepts filter=Q(...) to count or sum only matching rows, which turns several separate queries into one SQL statement with FILTER or CASE WHEN. Order matters: filters before values() restrict rows, filters after annotate() act like HAVING.

Full answer

Question to answer: for each subject, what is the average score and how many students scored 70 or more? A loop with several queries is slow; one grouped query is better.

python
Mark.objects.values("subject").annotate(
    avg=Avg("score"),
    high=Count("id", filter=Q(score__gte=70)),
    total=Sum("score"),
).order_by("subject")

How it works:

  • values("subject") before annotate() sets the GROUP BY. After annotate(), values() just selects columns.
  • filter=Q(...) is conditional aggregation. SQLite and PostgreSQL emit FILTER (WHERE ...), other backends use CASE WHEN.
  • aggregate(...) (not annotate) collapses the whole queryset into one dict, for example the overall average.
  • Without values(), annotate() groups by each row's primary key, giving per-object statistics such as Student.objects.annotate(total=Sum("marks__score")).

The order of filter() and annotate() changes results:

  • filter(...).annotate(Count("marks")) filters rows first, then counts only the matching marks.
  • annotate(Count("marks")).filter(marks__count__gt=1) becomes HAVING, filtering groups after counting.

Pitfalls: combining two multi-valued annotations (Count("marks") and Count("courses")) joins both tables, which multiplies rows and inflates counts; use distinct=True or Subquery. Default ordering from Meta.ordering used to alter GROUP BY, so call order_by() explicitly. Use Coalesce(Sum(...), 0) when empty groups should be 0 rather than None.

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.test.utils import CaptureQueriesContext


class ClassRoom(models.Model):
    name = models.CharField(max_length=10)
    class Meta:
        app_label = "school"


class Student(models.Model):
    name = models.CharField(max_length=40)
    class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    subject = models.CharField(max_length=20)
    score = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (ClassRoom, Student, Mark):
        editor.create_model(m)

a, b = ClassRoom.objects.create(name="10A"), ClassRoom.objects.create(name="10B")
for i, (name, room) in enumerate([("Asha", a), ("Ravi", a), ("Kiran", b), ("Meera", b)]):
    s = Student.objects.create(name=name, class_room=room)
    Mark.objects.create(student=s, subject="Maths", score=60 + i * 10)
    Mark.objects.create(student=s, subject="Science", score=55 + i * 8)

from django.db.models import Avg, Count, Q, Sum
from django.db.models.functions import Coalesce

stats = Mark.objects.values("subject").annotate(
    avg=Avg("score"), high=Count("id", filter=Q(score__gte=70)), total=Sum("score")
).order_by("subject")
for row in stats:
    print(row)

print(Mark.objects.aggregate(overall=Avg("score"), best=Sum("score", filter=Q(subject="Maths"))))

per_student = Student.objects.annotate(total=Sum("marks__score")).order_by("-total")
print([(s.name, s.total) for s in per_student])

# filter before annotate restricts the rows counted; filter after becomes HAVING
before = ClassRoom.objects.filter(students__marks__score__gte=80).annotate(n=Count("students__marks")).order_by("name")
after = ClassRoom.objects.annotate(n=Count("students__marks")).filter(n__gte=4).order_by("name")
print([(c.name, c.n) for c in before], [(c.name, c.n) for c in after])
print(Student.objects.filter(name="Nobody").aggregate(total=Coalesce(Sum("marks__score"), 0)))

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): {'subject': 'Maths', 'avg': 75.0, 'high': 3, 'total': 300} {'subject': 'Science', 'avg': 67.0, 'high': 2, 'total': 268} {'overall': 71.0, 'best': 300} [('Meera', 169), ('Kiran', 151), ('Ravi', 133), ('Asha', 115)] [('10B', 2)] [('10A', 4), ('10B', 4)] {'total': 0}

Key points

  • values() before annotate() defines GROUP BY
  • filter= on an aggregate gives conditional counts in one query
  • aggregate() returns one dict; annotate() adds per-row or per-group values
  • Order of filter() and annotate() changes the meaning
  • Two multi-valued annotations inflate counts; use distinct=True

Common mistakes

  • Running one query per group instead of values().annotate()
  • Forgetting order_by() and getting unexpected grouping
  • Combining two multi-valued Count annotations without distinct=True
  • Forgetting Coalesce so empty sums are None

Follow-ups

  • How would you compute a percentage of total per group?
  • What SQL does filter= generate on PostgreSQL versus MySQL?
  • How do you avoid inflated counts when joining two relations?

Tips

  • Show the values-then-annotate order
  • Explain the HAVING behaviour
  • Mention distinct=True
69.django-0069Mediummid

How do Subquery and OuterRef work in the Django ORM, and when do you choose them over joins or Python loops?

Subquery(queryset) embeds a queryset as a scalar subquery inside another query, and OuterRef("field") refers to a column of the outer query. Use it to annotate each row with a value taken from a related table that needs ordering or LIMIT, such as each student's best mark, without per-row queries or duplicate rows from joins. The inner queryset must return one column and at most one row.

Full answer

Problem: list every student with the score and subject of their highest mark. A join gives one row per mark; a Python loop gives N+1 queries. A correlated subquery gives exactly one value per student in one statement.

python
best = Mark.objects.filter(student=OuterRef("pk")).order_by("-score")
Student.objects.annotate(
    best_score=Subquery(best.values("score")[:1]),
    best_subject=Subquery(best.values("subject")[:1]),
)

Rules:

  • The inner queryset must select a single column (values("score")) and must be limited to one row ([:1]), otherwise the database raises an error ("more than one row returned").
  • OuterRef("pk") is resolved against the outer query when the subquery is executed. OuterRef(OuterRef("x")) reaches two levels up.
  • Subqueries can also appear in filter(): Student.objects.filter(id__in=Mark.objects.filter(score__gt=70).values("student")).
  • If the subquery may return no row, the annotation is NULL; add Coalesce(Subquery(...), 0) with output_field for a default.
  • Provide output_field when Django cannot infer the type of the result.

Choose by need: select_related and prefetch_related for fetching related objects, annotate(Count/Sum) for aggregates over a relation, Subquery for "latest or top row per group" and cases needing ordering and LIMIT, and Exists for yes or no questions.

Check the SQL with str(qs.query) and measure with explain(); correlated subqueries run per outer row, which is fine with an index on the foreign key (Mark.student, indexed by default).

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.test.utils import CaptureQueriesContext


class ClassRoom(models.Model):
    name = models.CharField(max_length=10)
    class Meta:
        app_label = "school"


class Student(models.Model):
    name = models.CharField(max_length=40)
    class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    subject = models.CharField(max_length=20)
    score = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (ClassRoom, Student, Mark):
        editor.create_model(m)

a, b = ClassRoom.objects.create(name="10A"), ClassRoom.objects.create(name="10B")
for i, (name, room) in enumerate([("Asha", a), ("Ravi", a), ("Kiran", b), ("Meera", b)]):
    s = Student.objects.create(name=name, class_room=room)
    Mark.objects.create(student=s, subject="Maths", score=60 + i * 10)
    Mark.objects.create(student=s, subject="Science", score=55 + i * 8)

from django.db.models import OuterRef, Subquery, IntegerField
from django.db.models.functions import Coalesce

best = Mark.objects.filter(student=OuterRef("pk")).order_by("-score")
qs = Student.objects.annotate(
    best_score=Subquery(best.values("score")[:1]),
    best_subject=Subquery(best.values("subject")[:1]),
).order_by("name")

with CaptureQueriesContext(connection) as ctx:
    rows = [(s.name, s.best_score, s.best_subject) for s in qs]
print(rows)
print("queries:", len(ctx))

weak = Student.objects.filter(id__in=Mark.objects.filter(score__lt=58).values("student"))
print([s.name for s in weak])

newcomer = Student.objects.create(name="Newcomer", class_room=ClassRoom.objects.first())
safe = Student.objects.filter(pk=newcomer.pk).annotate(
    best=Coalesce(Subquery(best.values("score")[:1]), 0, output_field=IntegerField())
).get()
print(safe.best)
print("(SELECT" in str(qs.query))

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', 60, 'Maths'), ('Kiran', 80, 'Maths'), ('Meera', 90, 'Maths'), ('Ravi', 70, 'Maths')] queries: 1 ['Asha'] 0 True

Key points

  • Subquery embeds a queryset; OuterRef points to the outer row
  • Inner query must return one column and one row
  • Gives per-row values without N+1 or duplicate join rows
  • NULL when the subquery is empty; use Coalesce
  • Index the foreign key used in the correlation

Common mistakes

  • Returning several columns or several rows from the inner queryset
  • Forgetting [:1] on an ordered inner queryset
  • Looping in Python and querying per object
  • Not providing output_field when Django cannot infer it

Follow-ups

  • How does Subquery differ from Exists?
  • How would you get the latest 3 marks per student?
  • When does a window function replace a subquery?

Tips

  • Explain correlation with OuterRef
  • State the one-column, one-row rule
  • Compare with joins and prefetch
70.django-0070Mediummid

How do you use Exists() in Django to filter or annotate rows based on related data, and why is it better than count() or a join?

Exists(queryset) produces a SQL EXISTS subquery that stops at the first matching row. It can be used inside filter() to select rows with related matches, or in annotate() to add a boolean field. It avoids duplicates from joins, avoids counting every row, and negates cleanly with ~Exists(...). For a single object, queryset.exists() is the cheapest check.

Full answer

Question: which students have at least one mark of 80 or above, and which have none?

python
high = Mark.objects.filter(student=OuterRef("pk"), score__gte=80)
Student.objects.filter(Exists(high))           # Django 3.0+: Exists works directly in filter
Student.objects.filter(~Exists(high))          # students with none
Student.objects.annotate(has_high=Exists(high))

Why Exists:

  • A join filter(marks__score__gte=80) returns one row per matching mark, so students appear several times unless you add distinct().
  • annotate(Count(...)).filter(count__gt=0) counts all matches before checking, doing needless work and forcing a GROUP BY.
  • EXISTS can stop scanning after the first hit, especially with an index on the foreign key.

Related tools:

  • qs.exists() on a queryset returns a Python bool with SELECT 1 ... LIMIT 1. Prefer it over if qs: (loads all rows) and over qs.count() > 0 (counts all).
  • ~Exists(...) makes anti-joins ("students without marks") more reliable than exclude(marks__isnull=False) in complicated cases and avoids the NOT IN with NULL trap.
  • Combine with Q: filter(Exists(high) | Q(name="Asha")) works because Exists is a boolean expression that can be combined with | and &, or annotate first and filter on the annotation.
  • Use Exists in Case/When to build derived labels.

The same OuterRef rules apply: the inner query is correlated to the outer row. Add .order_by() if the inner queryset has default ordering; Django strips ordering inside Exists, so it is harmless.

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.test.utils import CaptureQueriesContext


class ClassRoom(models.Model):
    name = models.CharField(max_length=10)
    class Meta:
        app_label = "school"


class Student(models.Model):
    name = models.CharField(max_length=40)
    class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    subject = models.CharField(max_length=20)
    score = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (ClassRoom, Student, Mark):
        editor.create_model(m)

a, b = ClassRoom.objects.create(name="10A"), ClassRoom.objects.create(name="10B")
for i, (name, room) in enumerate([("Asha", a), ("Ravi", a), ("Kiran", b), ("Meera", b)]):
    s = Student.objects.create(name=name, class_room=room)
    Mark.objects.create(student=s, subject="Maths", score=60 + i * 10)
    Mark.objects.create(student=s, subject="Science", score=55 + i * 8)

from django.db.models import Exists, OuterRef, Q

high = Mark.objects.filter(student=OuterRef("pk"), score__gte=80)
print("join duplicates:", Student.objects.filter(marks__score__gte=60).count(), "rows for", Student.objects.count(), "students")
print("exists:", [s.name for s in Student.objects.filter(Exists(high))])
print("not exists:", [s.name for s in Student.objects.filter(~Exists(high)).order_by("name")])

flagged = Student.objects.annotate(has_high=Exists(high)).order_by("name")
print([(s.name, s.has_high) for s in flagged])

mixed = Student.objects.filter(Exists(high) | Q(name="Asha")).order_by("name")
print([s.name for s in mixed])

print(Mark.objects.filter(score__gt=95).exists(), Mark.objects.filter(score__gt=50).exists())
print("LIMIT 1" in str(Mark.objects.filter(score__gt=50).query), "EXISTS" in str(Student.objects.filter(Exists(high)).query))

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): join duplicates: 7 rows for 4 students exists: ['Kiran', 'Meera'] not exists: ['Asha', 'Ravi'] [('Asha', False), ('Kiran', True), ('Meera', True), ('Ravi', False)] ['Asha', 'Kiran', 'Meera'] False True False True

Key points

  • Exists stops at the first match
  • Works in filter() and annotate(); negate with ~
  • Avoids duplicate rows from joins and the cost of counting
  • Use qs.exists() instead of count() > 0 or truthiness
  • Anti-joins are clearer than exclude() across relations

Common mistakes

  • Using count() > 0 or if queryset: just to check existence
  • Joining a multi-valued relation and forgetting duplicates
  • Using exclude() across multi-valued relations and getting surprising results
  • Thinking Exists needs a values() call or ordering

Follow-ups

  • How does exclude() on a multi-valued relation behave?
  • Why is NOT IN with NULLs dangerous?
  • How do you combine Exists with OR conditions?

Tips

  • Contrast with join and count
  • Mention ~Exists for anti-joins
  • Mention qs.exists()
71.django-0071Mediummid

How do Case and When expressions work in the Django ORM, and where are they useful?

Case(When(condition, then=value), ..., default=value) builds a SQL CASE expression. It can derive labels in annotate(), choose custom sort orders in order_by(), count conditionally inside aggregates, and update different rows with different values in one UPDATE statement. Always provide default and output_field when the result type is not obvious.

Full answer

A CASE expression moves if/else logic into the database, so it applies to millions of rows in one query.

python
grade = Case(
    When(score__gte=80, then=Value("A")),
    When(score__gte=60, then=Value("B")),
    default=Value("C"),
    output_field=CharField(),
)
Mark.objects.annotate(grade=grade)

Uses:

  1. Derived labels: grade bands, status text, price tiers (annotate).
  2. Custom ordering: order_by(Case(When(status="urgent", then=0), When(status="normal", then=1), default=2)), for example pinning urgent items first.
  3. Conditional aggregation: Sum(Case(When(paid=True, then="amount"), default=0)) (also expressible with filter=).
  4. Bulk conditional update: one statement instead of a loop, Mark.objects.update(score=Case(When(score__lt=40, then=40), default=F("score"))).
  5. Conditional values in filters: annotate first, then filter(grade="A").

Details:

  • When accepts lookups (score__gte=80), a Q object, or a boolean expression such as Exists(...).
  • then takes a value, an F() reference or any expression; use Value(...) for literals when mixing types.
  • Conditions are evaluated in order and the first match wins, so order from the most specific to the least.
  • Without default, unmatched rows become NULL.
  • When mixing types (integers and strings) specify output_field.

Prefer CASE over a Python loop when you only transform values; prefer a lookup table or a model method when the rule needs to change often or is shown in many places.

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.test.utils import CaptureQueriesContext


class ClassRoom(models.Model):
    name = models.CharField(max_length=10)
    class Meta:
        app_label = "school"


class Student(models.Model):
    name = models.CharField(max_length=40)
    class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    subject = models.CharField(max_length=20)
    score = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (ClassRoom, Student, Mark):
        editor.create_model(m)

a, b = ClassRoom.objects.create(name="10A"), ClassRoom.objects.create(name="10B")
for i, (name, room) in enumerate([("Asha", a), ("Ravi", a), ("Kiran", b), ("Meera", b)]):
    s = Student.objects.create(name=name, class_room=room)
    Mark.objects.create(student=s, subject="Maths", score=60 + i * 10)
    Mark.objects.create(student=s, subject="Science", score=55 + i * 8)

from django.db.models import Case, CharField, Count, F, IntegerField, Value, When

grade = Case(
    When(score__gte=80, then=Value("A")),
    When(score__gte=60, then=Value("B")),
    default=Value("C"),
    output_field=CharField(),
)
marks = Mark.objects.annotate(grade=grade).order_by("student__name", "subject")
print([(m.student.name, m.subject, m.score, m.grade) for m in marks.select_related("student")][:4])
print(list(Mark.objects.annotate(grade=grade).values("grade").annotate(n=Count("id")).order_by("grade")))

priority = Case(When(subject="Science", then=0), default=1, output_field=IntegerField())
print([(m.subject, m.score) for m in Mark.objects.order_by(priority, "-score")[:3]])

changed = Mark.objects.update(score=Case(When(score__lt=60, then=60), default=F("score")))
print(changed, "rows updated; lowest score now", min(Mark.objects.values_list("score", 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. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): [('Asha', 'Maths', 60, 'B'), ('Asha', 'Science', 55, 'C'), ('Kiran', 'Maths', 80, 'A'), ('Kiran', 'Science', 71, 'B')] [{'grade': 'A', 'n': 2}, {'grade': 'B', 'n': 5}, {'grade': 'C', 'n': 1}] [('Science', 79), ('Science', 71), ('Science', 63)] 8 rows updated; lowest score now 60

Key points

  • Case/When is SQL CASE: evaluated in order, first match wins
  • Use in annotate, order_by, aggregates and update
  • Provide default and output_field
  • A single UPDATE can apply different values by condition
  • Prefer it over Python loops for bulk transforms

Common mistakes

  • Forgetting default and getting NULL for unmatched rows
  • Ordering conditions from least to most specific
  • Mixing value types without output_field
  • Looping in Python to update rows that one CASE update could handle

Follow-ups

  • How would you use Case/When to pin certain rows first in a list?
  • How does conditional aggregation with filter= compare?
  • How do you update rows with different values in a single query?

Tips

  • Show a grade-band example
  • Mention first match wins
  • Mention bulk update
72.django-0072Mediummid

How do you use window functions such as Rank, Lag and running totals with Django's Window expression, and how do they differ from aggregation?

A window function computes a value for each row using a set of related rows (the window) without collapsing rows like GROUP BY does. In Django you wrap functions such as Rank, DenseRank, RowNumber, Lag, Lead or Sum in Window(expression, partition_by=..., order_by=...). Since Django 4.2 you can filter directly on a window annotation, for example to get the top 2 per group.

Full answer

Aggregation collapses rows: one row per group. Window functions keep every row and add a computed column.

python
Mark.objects.annotate(
    rank=Window(Rank(), partition_by=F("subject"), order_by=F("score").desc())
)

Parts of Window:

  • expression: Rank(), DenseRank(), RowNumber(), Lag("score"), Lead("score"), FirstValue, NthValue, Ntile(4), or an aggregate like Sum("score").
  • partition_by: restarts the calculation per group (here per subject).
  • order_by: defines order inside each partition. For Sum, an ordered window gives a running total.
  • frame: RowRange(start=-2, end=0) for moving averages.

Typical uses: top N per group, ranking with ties (Rank leaves gaps, DenseRank does not, RowNumber is unique), previous-row differences (Lag), running totals, percentiles via Ntile and share of total (F("score") / Window(Sum("score"))).

Filtering: before Django 4.2 you had to wrap the query in a subquery. In 4.2 and later, .filter(rank__lte=2) works directly on the annotation and Django wraps the query for you.

Support: SQLite 3.25+, PostgreSQL, MySQL 8+, MariaDB 10.2+, Oracle. Window expressions cannot be mixed with aggregates in some ways, and very large partitions need indexes matching partition_by and order_by for speed.

Choose window functions over Python processing when ranking or comparing neighbouring rows, because the database does it in one pass.

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.test.utils import CaptureQueriesContext


class ClassRoom(models.Model):
    name = models.CharField(max_length=10)
    class Meta:
        app_label = "school"


class Student(models.Model):
    name = models.CharField(max_length=40)
    class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    subject = models.CharField(max_length=20)
    score = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (ClassRoom, Student, Mark):
        editor.create_model(m)

a, b = ClassRoom.objects.create(name="10A"), ClassRoom.objects.create(name="10B")
for i, (name, room) in enumerate([("Asha", a), ("Ravi", a), ("Kiran", b), ("Meera", b)]):
    s = Student.objects.create(name=name, class_room=room)
    Mark.objects.create(student=s, subject="Maths", score=60 + i * 10)
    Mark.objects.create(student=s, subject="Science", score=55 + i * 8)

from django.db.models import F, Sum, Window
from django.db.models.functions import DenseRank, Lag, RowNumber, Rank

ranked = Mark.objects.annotate(
    rank=Window(Rank(), partition_by=F("subject"), order_by=F("score").desc()),
).order_by("subject", "rank")
print([(m.subject, m.student.name, m.score, m.rank) for m in ranked.select_related("student")][:4])

top2 = Mark.objects.annotate(
    rn=Window(RowNumber(), partition_by=F("subject"), order_by=F("score").desc())
).filter(rn__lte=2).order_by("subject", "rn")
print([(m.subject, m.score) for m in top2])

running = Mark.objects.filter(subject="Maths").annotate(
    prev=Window(Lag("score"), order_by=F("score").asc()),
    running=Window(Sum("score"), order_by=F("score").asc()),
).order_by("score")
print([(m.score, m.prev, m.running) for m in running])

share = Mark.objects.filter(subject="Science").annotate(pct=100 * F("score") / Window(Sum("score"))).order_by("score")
print([round(m.pct, 1) for m in share])

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. Needs SQLite 3.25 or newer (any modern Python build). Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): [('Maths', 'Meera', 90, 1), ('Maths', 'Kiran', 80, 2), ('Maths', 'Ravi', 70, 3), ('Maths', 'Asha', 60, 4)] [('Maths', 90), ('Maths', 80), ('Science', 79), ('Science', 71)] [(60, None, 60), (70, 60, 130), (80, 70, 210), (90, 80, 300)] [20, 23, 26, 29]

Key points

  • Windows keep all rows; aggregation collapses them
  • partition_by restarts per group; order_by orders inside it
  • Rank has gaps, DenseRank does not, RowNumber is unique
  • Lag/Lead read neighbouring rows; ordered Sum gives running totals
  • Django 4.2+ can filter on window annotations

Common mistakes

  • Expecting Window to reduce rows like aggregate()
  • Forgetting order_by inside Window for rank and running totals
  • Confusing Rank, DenseRank and RowNumber with ties
  • Filtering on window values in a way not supported before Django 4.2

Follow-ups

  • How do you get the latest row per group using a window function?
  • What is the difference between a frame and a partition?
  • How does this compare with a correlated subquery?

Tips

  • Define partition and order
  • Contrast Rank and DenseRank
  • Mention filtering on windows in 4.2
73.django-0073Mediummid

What are Django's database functions such as Coalesce, Concat, Lower, Cast and TruncMonth, and why use them instead of Python?

Django wraps many SQL functions (Coalesce, Concat, Lower, Upper, Length, Cast, Greatest, Now, TruncDate, TruncMonth, ExtractYear and more) in django.db.models.functions. They run inside the database, can be used in annotate, filter, order_by, update and indexes, and avoid fetching rows just to transform them in Python.

Full answer

Doing the work in SQL saves transferring rows and lets the database use indexes and sorting.

Common functions:

  • Coalesce("nickname", "name", Value("unknown")): first non-NULL value. Useful for defaults and null-safe sums.
  • Concat("first", Value(" "), "last"): string joining. Use output_field=CharField() when mixing types.
  • Lower("email"), Upper, Length, Trim, Substr, Replace.
  • Cast("score", FloatField()): type conversion for division or comparison.
  • Greatest, Least, Abs, Round, Floor, Mod.
  • Dates: TruncMonth("joined"), TruncDate("created_at"), ExtractYear, ExtractWeekDay, Now(). Time zone handling follows USE_TZ and the current time zone, which matters for day boundaries.

Uses:

python
Student.objects.annotate(month=TruncMonth("joined")).values("month").annotate(n=Count("id"))
Student.objects.filter(email__iexact="x@example.com")   # or annotate(Lower("email")) and filter on it
Student.objects.update(name=Upper("name"))

Functional indexes: models.Index(Lower("email"), name="email_lower_idx") makes case-insensitive lookups fast, and UniqueConstraint(Lower("email"), name=...) enforces case-insensitive uniqueness.

Cautions: custom Func subclasses can wrap any SQL function but may tie you to one database; division by an integer column uses integer division on some backends, so Cast first; and Coalesce needs compatible types for all arguments.

Writing your own is short: class Round2(Func): function = "ROUND"; template = "%(function)s(%(expressions)s, 2)".

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 datetime

from django.db import models, connection
from django.db.models import CharField, Count, F, FloatField, Value
from django.db.models.functions import Cast, Coalesce, Concat, Lower, TruncMonth, Upper


class Student(models.Model):
    first = models.CharField(max_length=20)
    last = models.CharField(max_length=20)
    nickname = models.CharField(max_length=20, null=True)
    email = models.CharField(max_length=40)
    marks = models.IntegerField()
    out_of = models.IntegerField()
    joined = models.DateField()

    class Meta:
        app_label = "school"
        indexes = [models.Index(Lower("email"), name="student_email_lower_idx")]


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

D = datetime.date
Student.objects.create(first="Asha", last="Rao", nickname="Ash", email="Asha@Example.com", marks=45, out_of=60, joined=D(2026, 1, 9))
Student.objects.create(first="Ravi", last="Iyer", nickname=None, email="ravi@example.com", marks=30, out_of=60, joined=D(2026, 1, 20))
Student.objects.create(first="Kiran", last="Shah", nickname=None, email="kiran@example.com", marks=50, out_of=60, joined=D(2026, 3, 2))

qs = Student.objects.annotate(
    full=Concat("first", Value(" "), "last", output_field=CharField()),
    display=Coalesce("nickname", "first"),
    pct=Cast("marks", FloatField()) * 100 / F("out_of"),
).order_by("id")
print([(s.full, s.display, round(s.pct, 1)) for s in qs])
print(list(Student.objects.filter(email__iexact="ASHA@example.com").values_list("first", flat=True)))
print(list(Student.objects.annotate(m=TruncMonth("joined")).values("m").annotate(n=Count("id")).order_by("m")))
Student.objects.update(last=Upper("last"))
print(list(Student.objects.order_by("id").values_list("last", 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. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): [('Asha Rao', 'Ash', 75.0), ('Ravi Iyer', 'Ravi', 50.0), ('Kiran Shah', 'Kiran', 83.3)] ['Asha'] [{'m': datetime.date(2026, 1, 1), 'n': 2}, {'m': datetime.date(2026, 3, 1), 'n': 1}] ['RAO', 'IYER', 'SHAH']

Key points

  • Database functions run in SQL, not Python
  • Coalesce gives the first non-NULL value
  • TruncMonth and Extract group by date parts
  • Cast avoids integer division surprises
  • Functional indexes and constraints accept expressions

Common mistakes

  • Pulling rows into Python just to lowercase or format them
  • Integer division when dividing two integer columns
  • Mixing types in Coalesce or Concat without output_field
  • Ignoring time zones when truncating datetimes to dates

Follow-ups

  • How do you build a case-insensitive unique constraint?
  • How would you write a custom Func?
  • How does TruncDate behave with USE_TZ?

Tips

  • Name functions from several groups
  • Mention functional indexes
  • Warn about integer division
74.django-0074Mediummid

What is the difference between save(), queryset.update() and bulk_update() in Django, in terms of queries, signals, auto_now fields and custom save logic?

save() loads nothing extra, runs the model's save() method and sends pre_save and post_save signals, and updates auto_now fields. queryset.update() issues a single UPDATE for all matching rows and skips save(), signals and auto_now. bulk_update(objs, fields) updates many objects in batches of CASE-based statements, also skipping save() and signals. Choose by whether you need side effects or speed.

Full answer
save()queryset.update()bulk_update()
SQLone UPDATE per objectone UPDATE for the whole queryseta few UPDATEs with CASE, batched
Custom save()runsskippedskipped
pre_save/post_save signalssentnot sentnot sent
auto_now fieldsrefreshednot touchednot touched
Needs objects in memoryyesnoyes
ReturnsNonerows matchedrows matched

When to use each:

  • save(): single objects and when your model has logic or listeners (audit log, cache invalidation). Pass update_fields=[...] to limit columns and avoid overwriting concurrent changes to other fields.
  • update(): the same change for many rows, ideally with F(): Fee.objects.filter(due__lt=today).update(amount=F("amount") + 50). It is atomic at the row level and the fastest. If you need auto_now, add updated=timezone.now() to the call.
  • bulk_update(): different values per object (for example after recalculating ranks in Python). Provide fields and a batch_size to keep statements within the database's parameter limit.

Consequences: code that relies on signals or save() overrides silently stops working when someone switches to update() for performance. Document this near the model, or put required side effects in a model manager or service function that is called deliberately. Also remember update() cannot be used on sliced querysets and cannot reference fields across joins directly.

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 datetime

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


class Fee(models.Model):
    roll_no = models.CharField(max_length=10)
    amount = models.IntegerField()
    updated = models.DateTimeField(auto_now=True)
    saves = models.IntegerField(default=0)

    class Meta:
        app_label = "school"

    def save(self, *args, **kwargs):
        self.saves += 1                                   # custom save() logic
        super().save(*args, **kwargs)


signals_seen = []


@receiver(post_save, sender=Fee)
def record(sender, instance, **kwargs):
    signals_seen.append(instance.roll_no)


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

Fee.objects.create(roll_no="A1", amount=100)
Fee.objects.create(roll_no="A2", amount=100)
signals_seen.clear()
Fee.objects.update(updated=datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc))     # freeze auto_now for the demo
old = Fee.objects.get(roll_no="A1").updated

print("update():", Fee.objects.update(amount=F("amount") + 50), "rows")
f = Fee.objects.get(roll_no="A1")
print("signals:", signals_seen, "| saves counter:", f.saves, "| auto_now changed:", f.updated != old)

f.amount = 999
f.save()
f = Fee.objects.get(roll_no="A1")
print("save():  signals:", signals_seen, "| saves counter:", f.saves, "| auto_now changed:", f.updated != old)

fees = list(Fee.objects.order_by("roll_no"))
for i, fee in enumerate(fees):
    fee.amount = 10 * (i + 1)
print("bulk_update():", Fee.objects.bulk_update(fees, ["amount"]), "rows | signals:", signals_seen)
print(list(Fee.objects.order_by("roll_no").values_list("amount", 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. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): update(): 2 rows signals: [] | saves counter: 1 | auto_now changed: False save(): signals: ['A1'] | saves counter: 2 | auto_now changed: True bulk_update(): 2 rows | signals: ['A1'] [10, 20]

Key points

  • save() runs custom logic, signals and auto_now
  • update() is one SQL statement and skips all of those
  • bulk_update() sets different values per object in batches
  • Use F() with update() for race-safe changes
  • Side effects need an explicit place when update() is used

Common mistakes

  • Switching save() to update() for speed and losing signals or custom logic
  • Expecting auto_now to change with update() or bulk_update()
  • Forgetting update_fields and overwriting concurrent changes
  • Using bulk_update without batch_size on very large lists

Follow-ups

  • How would you keep an audit log when using bulk operations?
  • What does save(update_fields=[...]) emit as SQL?
  • Why does update() not work on a sliced queryset?

Tips

  • Fill a comparison from memory
  • Name the side effects that are skipped
  • Mention F() with update()
75.django-0075Mediummid

How do squashmigrations, migration dependencies, merge migrations and RunSQL work in Django?

Each migration lists dependencies on earlier migrations, forming a graph. squashmigrations app 0001 0010 writes one migration with a replaces list that stands in for the originals until all environments have applied them, after which the old files can be deleted. If two branches create migrations with the same parent, makemigrations --merge creates a merge migration. RunSQL and RunPython hold hand-written changes and should be reversible.

Full answer

Migration files are nodes in a graph: dependencies = [("app", "0002_add_field")]. Django applies nodes in dependency order and records applied names in django_migrations.

Squashing: as an app collects hundreds of migrations, python manage.py squashmigrations app 0001 0010 creates 0001_squashed_0010_...py with replaces = [...]. Behaviour:

  • Databases that already applied all the replaced migrations are treated as having applied the squash; new databases run the single squashed migration.
  • Keep both sets of files until every environment has migrated past the squash, then delete the old files and the replaces line (and fix dependencies in other apps).
  • RunPython and RunSQL operations marked elidable=True are dropped during squashing. Others are kept, and a RunPython function defined inside a migration file cannot be copied safely: Django prints "Manual porting required" and the generated file refers to it with an invalid dotted path, so you must paste the function in by hand. Keeping data-migration functions in an importable helper module avoids this.
  • The squashed file is named 0001_squashed_0003_name.py, or 0001_initial_squashed_0003_name.py when it replaces an initial migration.
  • Squashing is an optimisation; do not do it while branches with unmerged migrations exist.

Conflicts: two developers add 0004_x and 0004_y from the same 0003. migrate fails with "Conflicting migrations detected". makemigrations --merge creates a migration depending on both leaves. Prefer rebasing and renumbering when the changes touch the same model.

Hand-written operations: migrations.RunSQL("CREATE INDEX ...", reverse_sql="DROP INDEX ...") for database features the ORM lacks, and RunPython(forward, backward). Use migrations.RunPython.noop as the reverse when nothing needs undoing. Use SeparateDatabaseAndState when the database change and Django's model state need to differ (for example renaming a table without a rename operation).

Useful commands: showmigrations, sqlmigrate app 0003, migrate app 0002 (roll back to a name), makemigrations --check, and migrate --plan.

python
import sys
import types

import io
import tempfile
from pathlib import Path

WORK = Path(tempfile.mkdtemp())
sys.path.insert(0, str(WORK))
pkg = WORK / "shopapp"
(pkg / "migrations").mkdir(parents=True)
(pkg / "__init__.py").write_text("")
(pkg / "migrations" / "__init__.py").write_text("")
(pkg / "models.py").write_text("""from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=40)
    sku = models.CharField(max_length=20, default="")
""")
(pkg / "migrations" / "0001_initial.py").write_text("""from django.db import migrations, models

class Migration(migrations.Migration):
    initial = True
    dependencies = []
    operations = [migrations.CreateModel("Product", [
        ("id", models.AutoField(primary_key=True, serialize=False)),
        ("name", models.CharField(max_length=40))])]
""")
(pkg / "migrations" / "0002_product_sku.py").write_text("""from django.db import migrations, models

class Migration(migrations.Migration):
    dependencies = [("shopapp", "0001_initial")]
    operations = [migrations.AddField("Product", "sku", models.CharField(max_length=20, default=""))]
""")
(pkg / "seeding.py").write_text("""def seed(apps, schema_editor):
    apps.get_model("shopapp", "Product").objects.create(name="Notebook", sku="NB-1")
""")
(pkg / "migrations" / "0003_index_and_seed.py").write_text("""from django.db import migrations
from shopapp.seeding import seed

class Migration(migrations.Migration):
    dependencies = [("shopapp", "0002_product_sku")]
    operations = [
        migrations.RunSQL("CREATE INDEX shop_sku_idx ON shopapp_product (sku)", reverse_sql="DROP INDEX shop_sku_idx"),
        migrations.RunPython(seed, migrations.RunPython.noop),
    ]
""")

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

from django.core.management import call_command

def run(*args, **kw):
    out = io.StringIO()
    call_command(*args, stdout=out, **kw)
    return out.getvalue().strip()

print(run("migrate", verbosity=0) or "migrated")
print(run("showmigrations", "shopapp"))
print([l for l in run("sqlmigrate", "shopapp", "0003").splitlines() if "CREATE INDEX" in l])
squash_log = run("squashmigrations", "shopapp", "0001", "0003", interactive=False)
print([line.strip() for line in squash_log.splitlines() if "Optimized" in line or "Manual porting" in line])

squashed = [p.name for p in (pkg / "migrations").glob("*squashed*.py")][0]
text = (pkg / "migrations" / squashed).read_text()
print(squashed)
print("replaces" in text, "RunSQL" in text, "RunPython" in text, "seeding" in text)
print(run("migrate", "shopapp", "0002", verbosity=0) or "rolled back to 0002")
print(run("showmigrations", "shopapp"))

Standalone script. It builds a small app named shopapp with three migrations in a temporary folder, then migrates, squashes and rolls back. A real project keeps these files under app/migrations/. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): migrated shopapp [X] 0001_initial [X] 0002_product_sku [X] 0003_index_and_seed ['CREATE INDEX shop_sku_idx ON shopapp_product (sku);'] ['Optimized from 4 operations to 3 operations.'] 0001_initial_squashed_0003_index_and_seed.py True True True True rolled back to 0002 shopapp [X] 0001_initial [X] 0002_product_sku [ ] 0003_index_and_seed

Key points

  • Migrations form a dependency graph recorded in django_migrations
  • Squash creates a migration with replaces; delete old files only when all environments are past it
  • makemigrations --merge resolves two leaf nodes
  • RunSQL and RunPython need reverse operations
  • sqlmigrate and migrate --plan show what will happen

Common mistakes

  • Deleting old migrations before every environment has applied them
  • Squashing while unmerged migration branches exist
  • Writing RunPython or RunSQL without a reverse operation
  • Resolving conflicts by editing numbers without checking dependencies

Follow-ups

  • How do you rename a table without losing data using SeparateDatabaseAndState?
  • What does migrate --fake do and when is it risky?
  • How do you safely roll back a data migration in production?

Tips

  • Describe the graph and django_migrations
  • Explain squash then clean up
  • Name RunSQL reverse_sql
76.django-0076Mediummid

How do you add filtering, searching and ordering to a Django REST Framework list endpoint with django-filter, SearchFilter and OrderingFilter?

Add filter backends to a generic view or viewset: DjangoFilterBackend (from django-filter) for exact and range filters declared by filterset_fields or a FilterSet class, SearchFilter for ?search= across search_fields, and OrderingFilter for ?ordering=. Whitelist the allowed fields, filter inside get_queryset() for permission-based scoping, and index the columns you filter on.

Full answer

Backends are applied in order to the queryset returned by get_queryset():

python
class StudentList(generics.ListAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ["grade", "class_room"]       # ?grade=A
    search_fields = ["name", "^roll_no"]              # ?search=asha  (^ means startswith)
    ordering_fields = ["name", "score"]               # ?ordering=-score
    ordering = ["name"]                               # default
  • django_filters.rest_framework.DjangoFilterBackend needs the django-filter package and "django_filters" in INSTALLED_APPS. For ranges and lookups, write a FilterSet: score_min = NumberFilter(field_name="score", lookup_expr="gte").
  • SearchFilter builds an OR of icontains across search_fields; prefixes ^ (startswith), = (exact), @ (full text on PostgreSQL), $ (regex). Searching related fields works with class_room__name.
  • OrderingFilter accepts only ordering_fields; leaving it unset allows any serializer field, which can expose columns or cause slow unindexed sorts. Always set it.
  • Invalid filter values return 400 with an error message (django-filter), so clients get feedback.

Design points:

  • Authorisation belongs in get_queryset() (for example Student.objects.filter(school=request.user.school)); filters then apply on top. Never trust a query parameter to scope data.
  • Set backends globally with DEFAULT_FILTER_BACKENDS or per view.
  • Filters on non-indexed columns and unbounded icontains on large tables are slow; use database indexes, trigram indexes on PostgreSQL, or a search engine.
  • Combine with pagination so filtered results are returned in pages.
  • Document filters: django-filter integrates with drf-spectacular for OpenAPI.
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", "django_filters", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection
from django_filters.rest_framework import DjangoFilterBackend, FilterSet, NumberFilter
from rest_framework import generics, serializers
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.test import APIClient


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

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Student)
for n, g, s in [("Asha", "A", 91), ("Ravi", "C", 58), ("Kiran", "B", 74), ("Meera", "B", 66)]:
    Student.objects.create(name=n, grade=g, score=s)


class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ["id", "name", "grade", "score"]


class StudentFilter(FilterSet):
    min_score = NumberFilter(field_name="score", lookup_expr="gte")

    class Meta:
        model = Student
        fields = ["grade", "min_score"]


class StudentList(generics.ListAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = StudentFilter
    search_fields = ["name"]
    ordering_fields = ["name", "score"]
    ordering = ["name"]


from django.urls import path
urlpatterns = [path("students/", StudentList.as_view())]

c = APIClient()
names = lambda r: [row["name"] for row in r.json()]
print(names(c.get("/students/")))
print(names(c.get("/students/", {"grade": "B"})))
print(names(c.get("/students/", {"min_score": 70, "ordering": "-score"})))
print(names(c.get("/students/", {"search": "ra"})))
r = c.get("/students/", {"ordering": "password"})            # not whitelisted: ignored
print(r.status_code, names(r))
r = c.get("/students/", {"min_score": "abc"})
print(r.status_code, r.json())

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`. Also needs `pip install django-filter`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3, django-filter 26.2): ['Asha', 'Kiran', 'Meera', 'Ravi'] ['Kiran', 'Meera'] ['Asha', 'Kiran'] ['Kiran', 'Meera', 'Ravi'] 200 ['Asha', 'Kiran', 'Meera', 'Ravi'] 400 {'min_score': ['Enter a number.']}

Key points

  • filter_backends compose: DjangoFilterBackend, SearchFilter, OrderingFilter
  • Whitelist filterset_fields and ordering_fields
  • FilterSet gives ranges and custom lookups
  • Scope by user in get_queryset(), not through parameters
  • Index filtered and sorted columns

Common mistakes

  • Leaving ordering_fields unset and exposing every column for sorting
  • Scoping data by a query parameter instead of get_queryset()
  • Running icontains searches on huge unindexed columns
  • Forgetting to add django_filters to INSTALLED_APPS

Follow-ups

  • How do you filter across a relationship or with a date range?
  • How would you make search fast on PostgreSQL?
  • How do you document filters in OpenAPI?

Tips

  • Name the three backends
  • Mention whitelisting
  • Mention scoping in get_queryset
77.django-0077Mediummid

How does API versioning work in Django REST Framework, and how do URLPathVersioning and AcceptHeaderVersioning differ?

DRF versioning schemes decide how the client names a version and expose it as request.version. URLPathVersioning puts it in the path (/api/v1/...), AcceptHeaderVersioning in the Accept media type parameter, NamespaceVersioning uses URL namespaces, and QueryParameterVersioning uses ?version=. The view reads request.version to choose serializers or behaviour, and DEFAULT_VERSION, ALLOWED_VERSIONS and VERSION_PARAM validate input.

Full answer

Versioning lets you change responses without breaking existing clients. Configure it in REST_FRAMEWORK:

python
REST_FRAMEWORK = {
    "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning",
    "DEFAULT_VERSION": "v1",
    "ALLOWED_VERSIONS": ["v1", "v2"],
}

Schemes:

  • URLPathVersioning: path("api/<version>/students/", ...). Visible, cache-friendly, easy to test with curl, and the most common choice.
  • AcceptHeaderVersioning: Accept: application/json; version=2. Keeps URLs stable, but is harder to cache and test.
  • NamespaceVersioning: separate include(..., namespace="v1") URLconfs.
  • QueryParameterVersioning: ?version=2; simple, but easy to omit.
  • HostNameVersioning: v2.api.example.com.

Inside a view: request.version holds the value, and reverse("student-list", request=request) builds URLs that include the version. Override get_serializer_class() to choose a different serializer:

python
def get_serializer_class(self):
    return StudentV2Serializer if self.request.version == "v2" else StudentV1Serializer

Unknown versions give 404 (URLPath) or 406 (Accept header) when ALLOWED_VERSIONS is set.

Practice:

  • Version only for breaking changes (removing or renaming fields, changing types). Adding optional fields is not breaking.
  • Keep the number of live versions small, announce deprecation (the Deprecation and Sunset headers), and share code through serializers that subclass each other.
  • Avoid copy-pasting whole viewsets for each version.
  • Test every supported version.
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__,
    REST_FRAMEWORK={
        "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning",
        "DEFAULT_VERSION": "v1",
        "ALLOWED_VERSIONS": ["v1", "v2"],
    },
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.test import APIClient
from rest_framework.views import APIView
from django.urls import path

class StudentV1(serializers.Serializer):
    name = serializers.CharField()


class StudentV2(StudentV1):
    roll_no = serializers.CharField()                      # additional field in the new version


class StudentDetail(APIView):
    def get(self, request, version):
        serializer_class = StudentV2 if request.version == "v2" else StudentV1
        return Response({"version": request.version, **serializer_class({"name": "Asha", "roll_no": "BCA-17"}).data})


urlpatterns = [path("api/<version>/students/1/", StudentDetail.as_view())]

c = APIClient()
print(c.get("/api/v1/students/1/").json())
print(c.get("/api/v2/students/1/").json())
print(c.get("/api/v3/students/1/").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`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {'version': 'v1', 'name': 'Asha'} {'version': 'v2', 'name': 'Asha', 'roll_no': 'BCA-17'} 404

Key points

  • Schemes: URL path, Accept header, namespace, query param, hostname
  • request.version drives serializer and behaviour choices
  • ALLOWED_VERSIONS rejects unknown versions
  • Only breaking changes need a new version
  • Keep live versions few and announce sunsets

Common mistakes

  • Creating a new version for every small change
  • Copy-pasting entire viewsets per version
  • Not setting ALLOWED_VERSIONS so any string is accepted
  • Forgetting to pass request to reverse() so URLs lose the version

Follow-ups

  • How would you deprecate and retire a version?
  • How do you version breaking changes in serializers without duplication?
  • Why is header-based versioning harder to cache?

Tips

  • List two schemes with trade-offs
  • Mention request.version
  • Say what counts as a breaking change
78.django-0078Mediummid

How do you handle writable nested serializers in Django REST Framework, and why must create() and update() be written by hand?

DRF supports nested serializers for reading out of the box, but it refuses to save nested data automatically because it cannot know how to create or match the children. For writable nesting, override create() and update(), pop the nested data from validated_data, wrap the work in transaction.atomic(), and decide how updates replace, add or remove children. Often, separate endpoints for children are simpler.

Full answer

Reading is easy: marks = MarkSerializer(many=True, read_only=True). Writing is not. If you pass a writable nested serializer to a ModelSerializer, DRF asserts that the default .create() does not support writable nested fields and tells you to write it explicitly.

Create pattern:

python
def create(self, validated_data):
    marks = validated_data.pop("marks")
    with transaction.atomic():
        student = Student.objects.create(**validated_data)
        Mark.objects.bulk_create([Mark(student=student, **m) for m in marks])
    return student

Update needs decisions that the framework cannot guess:

  • Replace all children (delete and recreate)? Simple, but changes child IDs.
  • Match by ID and update, create the new ones, delete the missing? Requires the child serializer to expose a writable id.
  • Reject changes to children and allow only parent fields?

PATCH makes this harder: if marks is absent, leave children alone; if present, apply your rule.

Practices:

  • Use transaction.atomic() so a failing child does not leave a half-created parent.
  • Validate nested data in the nested serializer (validate_<field>), and cross-check in the parent's validate().
  • Prevent N+1 on reads: prefetch_related("marks") in the queryset.
  • Use bulk_create for children where signals are not needed.
  • Consider flat APIs: POST /students/ then POST /students/1/marks/. They are easier to validate, authorise and document, and avoid large replace-all payloads.
  • For ModelSerializer with many=True nested fields, remember read_only nested fields are ignored on input.
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", "rest_framework", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection, transaction
from rest_framework import serializers


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

    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    subject = models.CharField(max_length=20)
    score = models.IntegerField()

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (Student, Mark):
        editor.create_model(m)


class MarkSerializer(serializers.ModelSerializer):
    class Meta:
        model = Mark
        fields = ["subject", "score"]


class StudentSerializer(serializers.ModelSerializer):
    marks = MarkSerializer(many=True)

    class Meta:
        model = Student
        fields = ["id", "name", "marks"]

    def create(self, validated_data):
        marks = validated_data.pop("marks")
        with transaction.atomic():
            student = Student.objects.create(**validated_data)
            Mark.objects.bulk_create([Mark(student=student, **m) for m in marks])
        return student

    def update(self, instance, validated_data):
        marks = validated_data.pop("marks", None)
        with transaction.atomic():
            instance.name = validated_data.get("name", instance.name)
            instance.save()
            if marks is not None:                                    # replace-all rule for this API
                instance.marks.all().delete()
                Mark.objects.bulk_create([Mark(student=instance, **m) for m in marks])
        return instance


s = StudentSerializer(data={"name": "Asha", "marks": [{"subject": "Maths", "score": 91}, {"subject": "Science", "score": 84}]})
s.is_valid(raise_exception=True)
student = s.save()
print(StudentSerializer(student).data)

bad = StudentSerializer(data={"name": "Ravi", "marks": [{"subject": "Maths", "score": "x"}]})
print(bad.is_valid(), bad.errors)
print("students after invalid input:", Student.objects.count())

patch = StudentSerializer(student, data={"marks": [{"subject": "Maths", "score": 95}]}, partial=True)
patch.is_valid(raise_exception=True)
patch.save()
print(StudentSerializer(Student.objects.get(pk=student.pk)).data["marks"])

class Naive(serializers.ModelSerializer):
    marks = MarkSerializer(many=True)
    class Meta:
        model = Student
        fields = ["name", "marks"]

try:
    n = Naive(data={"name": "Kiran", "marks": []})
    n.is_valid(raise_exception=True)
    n.save()
except AssertionError as exc:
    print("default create refused:", str(exc)[:55])

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): {'id': 1, 'name': 'Asha', 'marks': [{'subject': 'Maths', 'score': 91}, {'subject': 'Science', 'score': 84}]} False {'marks': {0: {'score': [ErrorDetail(string='A valid integer is required.', code='invalid')]}}} students after invalid input: 1 [{'subject': 'Maths', 'score': 95}] default create refused: The `.create()` method does not support writable nested

Key points

  • Nested reading works; nested writing needs explicit create() and update()
  • Pop nested data from validated_data first
  • Wrap parent and children writes in transaction.atomic()
  • Decide update semantics: replace, upsert or reject
  • Separate endpoints are often simpler

Common mistakes

  • Expecting ModelSerializer to save nested objects automatically
  • Skipping transaction.atomic() and leaving a half-created parent
  • Replacing children on PATCH when the field is absent
  • Causing N+1 queries when reading nested lists

Follow-ups

  • How would you implement upsert of children by ID?
  • When would you prefer separate endpoints for children?
  • How do you validate that a nested list has no duplicates?

Tips

  • Explain why DRF refuses
  • Show the pop-then-create pattern
  • Discuss update semantics
79.django-0079Mediummid

How do you add custom endpoints with @action and vary serializers, querysets and permissions per action in a DRF ViewSet?

The @action decorator on a ViewSet method adds an extra route such as /students/{id}/promote/ or /students/top/, registered automatically by the router. Inside a ViewSet, self.action names the current action, so you can override get_queryset(), get_serializer_class() and get_permissions() to return different values for list, retrieve, create or custom actions.

Full answer

Beyond CRUD, resources often need verbs: promote a student, export a list, mark as paid.

python
class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all()

    def get_serializer_class(self):
        return StudentListSerializer if self.action == "list" else StudentSerializer

    def get_permissions(self):
        if self.action in ("list", "retrieve"):
            return [IsAuthenticated()]
        return [IsAdminUser()]

    @action(detail=True, methods=["post"], url_path="promote")
    def promote(self, request, pk=None):
        student = self.get_object()
        ...
        return Response({"grade": student.grade})

    @action(detail=False, methods=["get"])
    def top(self, request):
        ...

Details:

  • detail=True makes a route on one object (/students/3/promote/) and get_object() applies queryset filtering, object permissions and 404 handling. detail=False makes a collection route (/students/top/).
  • url_path sets the URL segment; url_name sets the reverse name (student-promote).
  • Per-action overrides: @action(..., permission_classes=[IsAdminUser], serializer_class=PromoteSerializer) passes settings that apply only to that action.
  • get_serializer_class() is the standard hook for a light serializer in list views and a full one for detail views, which also reduces payload and queries.
  • get_queryset() can use self.action to add select_related for detail and only() for list.
  • Use POST (or PATCH) for state changes, not GET, so crawlers and prefetchers cannot trigger them.
  • Make actions idempotent where possible, and wrap multi-step changes in transaction.atomic().
  • Router registration (DefaultRouter().register("students", StudentViewSet)) picks up actions automatically.
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()

from django.contrib.auth import get_user_model
from django.db import models, connection
from django.urls import include, path
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.response import Response
from rest_framework.routers import DefaultRouter
from rest_framework.test import APIClient


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

    class Meta:
        app_label = "school"


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


class StudentBrief(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ["id", "name"]


class StudentFull(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ["id", "name", "grade"]


class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.order_by("id")

    def get_serializer_class(self):
        return StudentBrief if self.action == "list" else StudentFull

    def get_permissions(self):
        if self.action in ("list", "retrieve", "top"):
            return [IsAuthenticated()]
        return [IsAdminUser()]

    @action(detail=True, methods=["post"])
    def promote(self, request, pk=None):
        student = self.get_object()
        student.grade += 1
        student.save(update_fields=["grade"])
        return Response({"id": student.id, "grade": student.grade})

    @action(detail=False, methods=["get"])
    def top(self, request):
        best = self.get_queryset().order_by("-grade").first()
        return Response(StudentBrief(best).data)


router = DefaultRouter()
router.register("students", StudentViewSet)
urlpatterns = [path("api/", include(router.urls))]

Student.objects.create(name="Asha", grade=3)
Student.objects.create(name="Ravi")
staff = User.objects.create_user("teacher", password="x", is_staff=True)
pupil = User.objects.create_user("pupil", password="x")

c = APIClient()
print(c.get("/api/students/").status_code)
c.force_authenticate(pupil)
print(c.get("/api/students/").json())
print(c.get("/api/students/1/").json())
print(c.post("/api/students/1/promote/").status_code)
c.force_authenticate(staff)
print(c.post("/api/students/1/promote/").json())
c.force_authenticate(pupil)
print(c.get("/api/students/top/").json())
print(sorted({u.name for u in router.urls if u.name and "student" in u.name}))

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): 403 [{'id': 1, 'name': 'Asha'}, {'id': 2, 'name': 'Ravi'}] {'id': 1, 'name': 'Asha', 'grade': 3} 403 {'id': 1, 'grade': 4} {'id': 1, 'name': 'Asha'} ['student-detail', 'student-list', 'student-promote', 'student-top']

Key points

  • @action adds routes: detail=True per object, False for the collection
  • self.action lets you vary queryset, serializer and permissions
  • get_object() applies filtering and object permissions
  • Use POST for state-changing actions
  • Per-action permission_classes and serializer_class can be passed to the decorator

Common mistakes

  • Using GET for actions that change state
  • Registering permission rules in the decorator but forgetting default permissions
  • Duplicating whole viewsets instead of using self.action
  • Doing extra queries in list because the list serializer is as heavy as the detail one

Follow-ups

  • How does the router name the action routes for reverse()?
  • How do you add object-level permissions to get_object()?
  • How would you make promote idempotent?

Tips

  • Explain detail=True vs False
  • Use self.action to switch behaviour
  • Pick POST for state changes
80.django-0080Mediummid

How do you give a Django REST Framework API a consistent error format using a custom exception handler?

DRF converts APIException subclasses and Django's Http404 and PermissionDenied into responses through the function named by REST_FRAMEWORK['EXCEPTION_HANDLER']. A custom handler calls the default exception_handler(), then reshapes response.data into a single envelope, and can convert unexpected exceptions into a generic 500 while logging details. A stable error shape makes clients simpler.

Full answer

By default, errors look different per source: validation gives {"name": ["This field is required."]}, other exceptions give {"detail": "Not found."}. Clients then need several parsers.

A custom handler:

python
def api_exception_handler(exc, context):
    response = exception_handler(exc, context)         # DRF's default handler
    if response is None:                                # not an APIException, Http404 or PermissionDenied
        logger.exception("Unhandled error", extra={"view": context["view"].__class__.__name__})
        return Response({"error": {"code": "server_error", "message": "Something went wrong."}}, status=500)
    response.data = {"error": {"code": ..., "message": ..., "fields": ...}}
    return response

Configure: REST_FRAMEWORK = {"EXCEPTION_HANDLER": "myapp.errors.api_exception_handler"}.

Details:

  • exception_handler() returns None for exceptions it does not handle (anything other than APIException, Http404 and PermissionDenied). If your handler also returns None, DRF re-raises, so Django answers with its own 500 and error reporting sees the exception. Returning your own 500 response, as above, gives uniform JSON, but then you must log the exception yourself.
  • exc.get_codes() gives machine-readable codes (required, invalid), and exc.detail holds text, possibly nested. Do not leak internal messages for unexpected exceptions.
  • Add request_id or a documentation URL to the envelope for supportability. Consider RFC 9457 application/problem+json for a standard format.
  • Domain errors: define class DomainError(APIException) with status_code, default_detail and default_code, and raise them from services; the handler formats them.
  • Wrap with ATOMIC_REQUESTS carefully: DRF's handler marks the transaction for rollback with set_rollback() when a request is under ATOMIC_REQUESTS.
  • Test the shape for 400, 401, 403, 404, 405, 429 and 500 so the contract does not drift.
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", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.urls import path
from rest_framework import serializers, status
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.test import APIClient
from rest_framework.views import APIView, exception_handler
from rest_framework.settings import api_settings


def api_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if response is None:
        return Response({"error": {"code": "server_error", "message": "Something went wrong."}}, status=500)
    data = response.data
    if isinstance(data, dict) and set(data) != {"detail"}:
        error = {"code": "validation_error", "message": "Some fields are invalid.", "fields": data}
    else:
        detail = data["detail"]
        error = {"code": getattr(detail, "code", "error"), "message": str(detail)}
    response.data = {"error": error}
    return response


settings.REST_FRAMEWORK = {"EXCEPTION_HANDLER": "__main__.api_exception_handler"}
api_settings.reload()          # the settings object caches values, so reload after changing them at run time


class FeeClosed(APIException):
    status_code = status.HTTP_409_CONFLICT
    default_detail = "Fee window is closed."
    default_code = "fee_window_closed"


class In(serializers.Serializer):
    amount = serializers.IntegerField(min_value=1)


class Pay(APIView):
    def post(self, request, mode):
        if mode == "closed":
            raise FeeClosed()
        if mode == "boom":
            raise RuntimeError("database password is hunter2")
        In(data=request.data).is_valid(raise_exception=True)
        return Response({"ok": True})


urlpatterns = [path("pay/<str:mode>/", Pay.as_view())]
c = APIClient(raise_request_exception=False)
for mode, body in [("ok", {"amount": 0}), ("closed", {"amount": 5}), ("boom", {"amount": 5}), ("ok", {"amount": 5})]:
    r = c.post(f"/pay/{mode}/", body, format="json")
    print(r.status_code, r.json())
print(c.get("/pay/ok/").status_code, c.get("/pay/ok/").json())

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): 400 {'error': {'code': 'validation_error', 'message': 'Some fields are invalid.', 'fields': {'amount': ['Ensure this value is greater than or equal to 1.']}}} 409 {'error': {'code': 'fee_window_closed', 'message': 'Fee window is closed.'}} 500 {'error': {'code': 'server_error', 'message': 'Something went wrong.'}} 200 {'ok': True} 405 {'error': {'code': 'method_not_allowed', 'message': 'Method "GET" not allowed.'}}

Key points

  • Default error shapes differ by source
  • Wrap exception_handler() and reshape response.data
  • Returning None makes DRF re-raise, so Django answers with a 500
  • Domain errors can subclass APIException
  • Test every error status for contract stability

Common mistakes

  • Leaking exception messages from unexpected errors to clients
  • Returning different error shapes from different endpoints
  • Swallowing unexpected exceptions without logging
  • Forgetting to test non-validation errors such as 405 and 429

Follow-ups

  • How does RFC 9457 problem details compare to a custom envelope?
  • How would you attach a request ID to every error?
  • What does the handler receive in context?

Tips

  • Describe wrapping the default handler
  • Mention the None return for unknown exceptions
  • Mention domain exceptions