← Interview prep

Django interview questions

Models, ORM, auth, and Django web patterns.

100 questions · Page 2 of 5

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

Page 2 of 5

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

21.django-0021Mediummid

What is the difference between annotate() and aggregate() in the Django ORM?

aggregate() reduces the whole QuerySet to a single dict of values, such as the overall average mark. annotate() adds a computed value to each row, which becomes a GROUP BY when the expression uses an aggregate, such as the average mark per class. values() before annotate() picks the grouping columns.

Full answer

Both use aggregate functions such as Count, Sum, Avg, Max and Min, but they return different shapes.

aggregate() is terminal. It runs right away and returns a dict:

python
Mark.objects.aggregate(avg=Avg("score"), top=Max("score"))
# {'avg': 71.0, 'top': 90}

annotate() returns a QuerySet where each object gets a new attribute:

python
ClassRoom.objects.annotate(students_count=Count("students"))

SQL: SELECT ..., COUNT(student.id) FROM classroom LEFT JOIN student ... GROUP BY classroom.id.

Grouping by a column instead of by object uses values() first:

python
Mark.objects.values("subject").annotate(avg=Avg("score"))

Useful details:

  • Filter on the annotation with filter() after annotate (becomes HAVING): .annotate(n=Count("students")).filter(n__gte=2).
  • Conditional aggregation: Count("marks", filter=Q(marks__score__gte=75)).
  • Two Count annotations over different multi-valued relations multiply rows through the JOINs and give inflated numbers. Use distinct=True or subqueries.
  • Avg returns a float; Sum of an empty set returns None. Since Django 4.0, pass default=0 to get 0 instead.
  • Default ordering in Meta.ordering used to sneak into GROUP BY; since Django 3.1 it is ignored in these queries, but explicit order_by() fields still affect grouping.

Rule of thumb: one number for the whole set is aggregate; one number per row or group is annotate.

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, Max, Q, Sum

print(Mark.objects.aggregate(avg=Avg("score"), top=Max("score")))
print(Mark.objects.filter(score__gt=1000).aggregate(total=Sum("score", default=0)))

for room in ClassRoom.objects.annotate(
    students_count=Count("students", distinct=True),
    good=Count("students__marks", filter=Q(students__marks__score__gte=75)),
).order_by("name"):
    print(room.name, room.students_count, room.good)

per_subject = Mark.objects.values("subject").annotate(avg=Avg("score")).order_by("subject")
print(list(per_subject))

busy = ClassRoom.objects.annotate(n=Count("students")).filter(n__gte=2).values_list("name", flat=True)
print(list(busy))

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): {'avg': 71.0, 'top': 90} {'total': 0} 10A 2 0 10B 2 3 [{'subject': 'Maths', 'avg': 75.0}, {'subject': 'Science', 'avg': 67.0}] ['10A', '10B']

Key points

  • aggregate() returns a dict for the whole set
  • annotate() adds a value per row or group
  • values() before annotate() sets GROUP BY columns
  • Filter after annotate becomes HAVING
  • Multiple multi-valued Counts can inflate results

Common mistakes

  • Using annotate when you want one number, then looping to sum in Python
  • Counting across two multi-valued relations without distinct=True
  • Expecting Sum over no rows to be 0 without default=0
  • Forgetting values() and grouping by every model field

Follow-ups

  • How would you get the top scorer in each class in one query?
  • What is the difference between filter() before and after annotate()?
  • When would you use Subquery and OuterRef instead?

Tips

  • Give the output shape of each in one sentence
  • Show values().annotate() for GROUP BY
  • Mention the inflated count trap with multiple joins
22.django-0022Mediummid

How do class-based views work in Django, and how do you customise generic views like ListView and DetailView?

A class-based view is a class whose as_view() returns a function; dispatch() sends each request to a method named after the HTTP verb, such as get() or post(). Generic views like ListView, DetailView, CreateView and UpdateView implement common patterns, and you customise them by setting attributes (model, template_name, paginate_by) or overriding hooks such as get_queryset(), get_context_data() and form_valid().

Full answer

View.as_view() builds a function Django can call. For each request it creates a new instance of the class, stores request, args and kwargs on it, and calls dispatch(), which calls get(), post() and so on. A method that is not defined returns 405 Method Not Allowed.

Generic views are pre-built patterns:

  • ListView: a page of objects (object_list, pagination with paginate_by).
  • DetailView: one object looked up by pk or slug from the URL, 404 if missing.
  • CreateView / UpdateView / DeleteView: forms with redirect on success.
  • TemplateView, RedirectView, FormView.

They are built from mixins (MultipleObjectMixin, SingleObjectMixin, FormMixin), so the same hooks appear everywhere:

  • get_queryset(): which rows are visible. Put user scoping and select_related here.
  • get_object(): the single object for detail views.
  • get_context_data(**kwargs): add template variables; always call super() first.
  • form_valid(form): set fields like the owner before saving.
  • get_success_url().

Access control comes from mixins placed to the left of the view class: class MyLoans(LoginRequiredMixin, ListView). Python's method resolution order (MRO) runs left to right, so the mixin's dispatch() runs first.

When to choose them: CBVs reduce repetition for CRUD screens. A function view is often clearer for one-off logic with several branches. Many teams use both.

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.http import HttpResponse
from django.test import RequestFactory
from django.views import View
from django.views.generic import ListView


class Book(models.Model):
    title = models.CharField(max_length=60)
    owner = models.CharField(max_length=30)
    class Meta:
        app_label = "school"
        ordering = ["title"]


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

for t, o in [("Godan", "nisha"), ("Gitanjali", "nisha"), ("Nirmala", "tom")]:
    Book.objects.create(title=t, owner=o)


class MyBooks(ListView):
    model = Book
    paginate_by = 10

    def get_queryset(self):
        return super().get_queryset().filter(owner=self.kwargs["owner"])

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx["total"] = self.object_list.count()
        return ctx

    def render_to_response(self, context, **kwargs):
        titles = [b.title for b in context["object_list"]]
        return HttpResponse(f"{titles} total={context['total']}")


class Ping(View):
    def get(self, request):
        return HttpResponse("pong")


rf = RequestFactory()
print(MyBooks.as_view()(rf.get("/"), owner="nisha").content.decode())
print(Ping.as_view()(rf.get("/")).content.decode(), Ping.as_view()(rf.post("/")).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. render_to_response is overridden here only to avoid needing a template file. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['Gitanjali', 'Godan'] total=2 pong 405

Key points

  • as_view() creates a new instance per request and calls dispatch()
  • dispatch() routes to get(), post() and so on
  • Override get_queryset, get_context_data, form_valid
  • Mixins go to the left because of MRO
  • Missing method handlers return 405

Common mistakes

  • Storing request data on the class instead of the instance (class attributes are shared)
  • Overriding get_context_data without calling super()
  • Placing LoginRequiredMixin to the right of the view class
  • Filtering by user in the template instead of get_queryset()

Follow-ups

  • Explain the MRO for class MyView(LoginRequiredMixin, UpdateView)
  • How would you set the logged-in user as owner in CreateView?
  • When would you prefer a function view?

Tips

  • Describe the as_view -> dispatch -> get flow
  • Name three hooks and what each controls
  • Mention mixin ordering and why it matters
23.django-0023Mediummid

What is middleware in Django, and how do you write a custom middleware?

Middleware is a layer that wraps every request and response. It is a callable built once with get_response; on each request it can run code before calling get_response (the next layer and eventually the view) and after it returns. Order in the MIDDLEWARE setting matters: requests flow top to bottom and responses bottom to top. Extra hooks include process_view, process_exception and process_template_response.

Full answer

Think of middleware as a stack of wrappers around the view. Each entry in settings.MIDDLEWARE receives the request on the way in and the response on the way out.

The modern form is a factory that returns a callable:

python
class TimingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response   # runs once at startup

    def __call__(self, request):
        start = time.perf_counter()        # before the view
        response = self.get_response(request)
        response["X-Elapsed-ms"] = ...     # after the view
        return response

Order rules:

  • On the way in, middleware runs top to bottom. On the way out, bottom to top.
  • If a middleware returns a response without calling get_response, the layers below and the view are skipped, but the layers above still process the response.
  • Built-in order matters: SessionMiddleware must come before AuthenticationMiddleware, which needs the session to find request.user.

Optional hooks on the class:

  • process_view(request, view_func, view_args, view_kwargs): runs just before the view, after URL resolution.
  • process_exception(request, exception): runs when the view raises; return a response to handle it.
  • process_template_response(request, response): for responses with .render().

Typical uses: request IDs and logging, timing, adding security headers, maintenance mode, tenant detection from the host.

Async support: middleware can declare sync_capable / async_capable. In an ASGI deployment, a sync-only middleware forces Django to switch threads around it, which costs performance. For new middleware in async projects, support both modes (Django provides @sync_and_async_middleware).

Keep middleware cheap; it runs on every request, including static checks and health probes.

python
import sys
import types

import django
from django.conf import settings

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

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

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


class RequestIdMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.counter = 0

    def __call__(self, request):
        self.counter += 1
        request.request_id = f"req-{self.counter}"
        response = self.get_response(request)
        response["X-Request-ID"] = request.request_id
        return response


class MaintenanceMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.path.startswith("/fees/") and settings.FEES_LOCKED:
            return JsonResponse({"detail": "Fee payments are paused"}, status=503)
        return self.get_response(request)

    def process_exception(self, request, exception):
        return JsonResponse({"detail": "Something went wrong", "id": request.request_id}, status=500)


def fees(request):
    return HttpResponse("pay here")

def broken(request):
    raise ValueError("boom")

urlpatterns = [path("fees/", fees), path("broken/", broken)]
settings.ROOT_URLCONF = __name__
settings.FEES_LOCKED = False
settings.MIDDLEWARE = [f"{__name__}.RequestIdMiddleware", f"{__name__}.MaintenanceMiddleware"]

c = Client()
r = c.get("/fees/")
print(r.status_code, r["X-Request-ID"], r.content.decode())
settings.FEES_LOCKED = True
r = c.get("/fees/")
print(r.status_code, r["X-Request-ID"], r.json())
r = c.get("/broken/")
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. The counter on self is fine for a demo; in production use a UUID per request because instances are shared across threads. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 req-1 pay here 503 req-2 {'detail': 'Fee payments are paused'} 500 {'detail': 'Something went wrong', 'id': 'req-3'}

Key points

  • Middleware wraps every request and response
  • __init__ runs once; __call__ runs per request
  • Requests go top to bottom, responses bottom to top
  • Returning early skips the view and lower layers
  • Sync-only middleware slows ASGI apps

Common mistakes

  • Doing heavy work such as database queries in middleware on every request
  • Placing middleware in the wrong order, for example auth before sessions
  • Keeping per-request state on self (it is shared across requests and threads)
  • Writing sync-only middleware for an ASGI project

Follow-ups

  • How would you add a correlation ID that also appears in logs?
  • What is the difference between middleware and a view decorator?
  • How does Django handle sync middleware under ASGI?

Tips

  • Draw the onion: in top to bottom, out bottom to top
  • Show the __init__ vs __call__ difference
  • Name a real use case such as request IDs or security headers
24.django-0024Mediummid

What are Django signals, how do you use post_save, and when should you avoid signals?

Signals let one part of the code react to events sent elsewhere, such as post_save after a model is saved. You connect a receiver with @receiver(post_save, sender=Model) and usually register it in AppConfig.ready(). Signals run synchronously in the same transaction, are skipped by bulk operations and update(), and hide control flow, so explicit service functions are often clearer.

Full answer

A signal is an event with subscribers. Built-in model signals include pre_save, post_save, pre_delete, post_delete and m2m_changed. There are also request signals (request_started, request_finished) and auth signals (user_logged_in, user_login_failed).

Connecting a receiver:

python
@receiver(post_save, sender=Student)
def create_report_card(sender, instance, created, **kwargs):
    if created:
        ReportCard.objects.create(student=instance)

Put receivers in signals.py and import it in AppConfig.ready() so they register once at startup.

Facts that matter in interviews:

  • Signals are synchronous. The receiver runs inside save(), in the same thread and database transaction. A slow receiver slows the request; an exception in it bubbles up to the caller.
  • QuerySet.update(), bulk_create() (no post_save per object), bulk_update() and raw SQL do not send pre_save/post_save.
  • created tells you whether this was an insert.
  • Use dispatch_uid to avoid connecting the same receiver twice.
  • If a receiver sends email or calls an API, wrap it in transaction.on_commit() so it only fires after the data is really committed.

When to avoid them: if the reacting code lives in your own app, calling a service function directly (enrol_student() that creates the student and the report card) is easier to read, test and debug. Signals shine when you need to react to models you do not own, such as a third-party app's User, or when a reusable app wants to let other apps hook in without importing 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()

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


class Student(models.Model):
    name = models.CharField(max_length=40)
    class Meta:
        app_label = "school"


class ReportCard(models.Model):
    student = models.OneToOneField(Student, on_delete=models.CASCADE)
    class Meta:
        app_label = "school"


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

outbox = []


@receiver(post_save, sender=Student, dispatch_uid="student_report_card")
def create_report_card(sender, instance, created, **kwargs):
    if created:
        ReportCard.objects.create(student=instance)
        transaction.on_commit(lambda: outbox.append(f"welcome mail to {instance.name}"))


with transaction.atomic():
    s = Student.objects.create(name="Dev")
    print("inside transaction, outbox:", outbox)
print("after commit, outbox:", outbox)
print("report card exists:", ReportCard.objects.filter(student=s).exists())

s.name = "Dev Patel"
s.save()  # created=False, no second card
print("cards:", ReportCard.objects.count())

Student.objects.bulk_create([Student(name="Lina")])
print("cards after bulk_create:", ReportCard.objects.count())

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): inside transaction, outbox: [] after commit, outbox: ['welcome mail to Dev'] report card exists: True cards: 1 cards after bulk_create: 1

Key points

  • Signals are synchronous and share the caller's transaction
  • Register receivers in AppConfig.ready()
  • update(), bulk ops and raw SQL skip save signals
  • Use on_commit for side effects like emails
  • Prefer explicit service functions for your own models

Common mistakes

  • Expecting post_save to run after bulk_create() or update()
  • Sending emails directly in a receiver before the transaction commits
  • Using signals for logic inside your own app, making the flow hard to follow
  • Registering receivers in models.py imports that run twice, without dispatch_uid

Follow-ups

  • How would you test a signal receiver in isolation?
  • What happens if a post_save receiver raises an exception?
  • How is m2m_changed different from post_save?

Tips

  • State that signals are synchronous, many candidates think they are async
  • List the operations that skip signals
  • Give one case where signals are the right tool and one where they are not
25.django-0025Mediummid

Why should you set up a custom user model at the start of a Django project, and how do you do it?

Changing AUTH_USER_MODEL after the first migration is hard because every foreign key to the user table is tied to it. Starting with class User(AbstractUser) and AUTH_USER_MODEL = "accounts.User" costs nothing and lets you add fields like phone or roll number later. Refer to the user through settings.AUTH_USER_MODEL in models and get_user_model() in code.

Full answer

Django's default auth.User works, but projects often need changes later: log in with email, add a phone number, a role, or a student roll number. Once migrations have created auth_user and other tables point at it, switching to a different model means rewriting foreign keys and migrating data by hand. The Django docs strongly recommend a custom user model for every new project.

Setup, before the first migrate:

python
# accounts/models.py
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    phone = models.CharField(max_length=15, blank=True)

# settings.py
AUTH_USER_MODEL = "accounts.User"

Then register it in the admin (admin.site.register(User, UserAdmin)), and run makemigrations and migrate.

Choosing a base:

  • AbstractUser: keeps username, names, email, staff flags and permissions. Add fields. The usual choice.
  • AbstractBaseUser + PermissionsMixin: start almost from scratch (only password and last_login). Use it for email-only login or a very different identity model. You must write a manager with create_user and create_superuser, and set USERNAME_FIELD and REQUIRED_FIELDS.

Referring to the user:

  • In model fields: models.ForeignKey(settings.AUTH_USER_MODEL, ...), never User imported directly.
  • In code: get_user_model().

Profile model vs custom user: extra data that only some features need (a teacher's subject list) can live in a separate Profile with a OneToOneField. Data needed on every request or for login belongs on the user model.

python
import sys
import types

import django
from django.conf import settings

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

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

from django.contrib.auth.models import AbstractUser, Group, Permission
from django.db import models, connection


class User(AbstractUser):
    phone = models.CharField(max_length=15, blank=True)
    roll_no = models.CharField(max_length=12, blank=True)

    # Two user models exist in this demo (auth.User and this one), so the
    # reverse names below must not clash. A real project only has one.
    groups = models.ManyToManyField(Group, blank=True, related_name="school_users")
    user_permissions = models.ManyToManyField(Permission, blank=True, related_name="school_users")

    class Meta:
        app_label = "school"


class Loan(models.Model):
    member = models.ForeignKey("school.User", on_delete=models.CASCADE, related_name="loans")
    book = models.CharField(max_length=60)
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (User, Loan):
        editor.create_model(m)

u = User.objects.create_user("tara", password="Library#2026", phone="98xxxxxx01", roll_no="BCA-17")
Loan.objects.create(member=u, book="Ignited Minds")
print(u.username, u.phone, u.roll_no, u.check_password("Library#2026"))
print([l.book for l in u.loans.all()])
print([f.name for f in User._meta.get_fields() if f.name in ("phone", "roll_no", "is_staff")])

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. In a real project AUTH_USER_MODEL points to this class and auth.User is not used; the related_name overrides exist only because both models live in one demo file. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): tara 98xxxxxx01 BCA-17 True ['Ignited Minds'] ['is_staff', 'phone', 'roll_no']

Key points

  • Set AUTH_USER_MODEL before the first migration
  • AbstractUser for adding fields, AbstractBaseUser for full control
  • Use settings.AUTH_USER_MODEL in ForeignKeys
  • Use get_user_model() in code
  • Profile models suit optional per-feature data

Common mistakes

  • Starting with auth.User and trying to swap it after production data exists
  • Importing User directly in ForeignKeys instead of settings.AUTH_USER_MODEL
  • Using AbstractBaseUser without writing a proper manager
  • Forgetting to register the custom user with UserAdmin

Follow-ups

  • How would you make email the login field?
  • How would you migrate an existing project from auth.User to a custom model?
  • When is a Profile model better than adding fields to User?

Tips

  • Say why it must happen before the first migration
  • Compare AbstractUser and AbstractBaseUser
  • Mention settings.AUTH_USER_MODEL and get_user_model()
26.django-0026Mediummid

How do you write a data migration in Django with RunPython, and what rules should it follow?

Create an empty migration with makemigrations --empty app, then add migrations.RunPython(forward, backward). Inside the functions, get models with apps.get_model("app", "Model") so you use the historical version that matches that point in history, not the current class. Provide a reverse function (or RunPython.noop), batch large updates, and keep schema and data changes in separate migrations on databases that cannot mix them in one transaction.

Full answer

Schema migrations change tables. Data migrations change rows, for example filling a new full_name field from first_name and last_name, or converting grades "A/B/C" to marks ranges.

Steps:

  1. python manage.py makemigrations school --empty --name fill_full_name
  2. Edit the file:
python
def forwards(apps, schema_editor):
    Student = apps.get_model("school", "Student")
    for s in Student.objects.filter(full_name=""):
        s.full_name = f"{s.first_name} {s.last_name}".strip()
        s.save(update_fields=["full_name"])

class Migration(migrations.Migration):
    dependencies = [("school", "0004_student_full_name")]
    operations = [migrations.RunPython(forwards, migrations.RunPython.noop)]

Rules:

  • Use apps.get_model(). Importing from school.models import Student gives you today's model, which may have fields that do not exist yet at this migration. Historical models also have no custom methods and no custom save(); managers are only available if marked use_in_migrations = True.
  • Give a reverse function, or RunPython.noop when reversing needs no data change, so migrate school 0004 still works.
  • Large tables: process in batches with iterator() and bulk_update(), or use update() with expressions. One huge transaction can lock the table and fill logs.
  • Signals do not fire for historical models in a useful way; do the work explicitly.
  • On PostgreSQL, schema and data changes can share a transaction. Still, splitting "add nullable column", "fill data" and "make non-null" into separate migrations makes deploys safer.
  • RunSQL exists for raw SQL, with reverse_sql.

Test data migrations against a copy of production data before deploying.

python
import os
import sys
import tempfile
from pathlib import Path

root = Path(tempfile.mkdtemp())
app = root / "school"
(app / "migrations").mkdir(parents=True)
(app / "__init__.py").write_text("")
(app / "migrations" / "__init__.py").write_text("")
(app / "models.py").write_text(
    "from django.db import models\n\n"
    "class Student(models.Model):\n"
    "    first_name = models.CharField(max_length=30)\n"
    "    last_name = models.CharField(max_length=30)\n"
    "    full_name = models.CharField(max_length=61, blank=True, default='')\n"
)
(app / "migrations" / "0001_initial.py").write_text("""
from django.db import migrations, models

class Migration(migrations.Migration):
    initial = True
    dependencies = []
    operations = [
        migrations.CreateModel(name="Student", fields=[
            ("id", models.BigAutoField(primary_key=True, serialize=False)),
            ("first_name", models.CharField(max_length=30)),
            ("last_name", models.CharField(max_length=30)),
        ]),
        migrations.RunPython(
            lambda apps, se: apps.get_model("school", "Student").objects.bulk_create([
                apps.get_model("school", "Student")(first_name="Isha", last_name="Verma"),
                apps.get_model("school", "Student")(first_name="Omar", last_name="Khan"),
            ]),
            migrations.RunPython.noop,
        ),
    ]
""")
(app / "migrations" / "0002_student_full_name.py").write_text("""
from django.db import migrations, models

class Migration(migrations.Migration):
    dependencies = [("school", "0001_initial")]
    operations = [migrations.AddField("student", "full_name",
                  models.CharField(max_length=61, blank=True, default=""))]
""")
(app / "migrations" / "0003_fill_full_name.py").write_text("""
from django.db import migrations

def forwards(apps, schema_editor):
    Student = apps.get_model("school", "Student")
    batch = []
    for s in Student.objects.filter(full_name="").iterator(chunk_size=500):
        s.full_name = f"{s.first_name} {s.last_name}".strip()
        batch.append(s)
    Student.objects.bulk_update(batch, ["full_name"], batch_size=500)

def backwards(apps, schema_editor):
    apps.get_model("school", "Student").objects.update(full_name="")

class Migration(migrations.Migration):
    dependencies = [("school", "0002_student_full_name")]
    operations = [migrations.RunPython(forwards, backwards)]
""")
sys.path.insert(0, str(root))

import django
from django.conf import settings

settings.configure(
    INSTALLED_APPS=["school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.core.management import call_command
from school.models import Student

call_command("migrate", "school", verbosity=0)
print(list(Student.objects.order_by("id").values_list("full_name", flat=True)))
call_command("migrate", "school", "0002", verbosity=0)
print(list(Student.objects.order_by("id").values_list("full_name", flat=True)))

Standalone script. It writes a small app with three migrations (create, add field, data migration) to a temporary folder, migrates forward, then rolls back to 0002 to show the reverse function. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['Isha Verma', 'Omar Khan'] ['', '']

Key points

  • Create with makemigrations --empty, add RunPython
  • Always use apps.get_model() for historical models
  • Provide a reverse function or RunPython.noop
  • Batch large updates
  • Split add column, fill, and constrain into separate steps

Common mistakes

  • Importing the current model class inside a migration
  • Leaving out a reverse function so the migration cannot be rolled back
  • Updating millions of rows in one transaction and locking the table
  • Calling custom model methods that do not exist on historical models

Follow-ups

  • Why does apps.get_model() exist?
  • How would you backfill a column on a 50-million-row table without downtime?
  • What does RunPython.noop do?

Tips

  • Explain historical models clearly, it is the main trap
  • Mention batching and reversibility
  • Tie data migrations to the safe add-fill-constrain sequence
27.django-0027Mediummid

How do database transactions work in Django? Explain atomic(), savepoints and transaction.on_commit().

By default Django runs in autocommit mode: each query commits on its own. transaction.atomic() groups queries so they all commit or all roll back; nested atomic blocks create savepoints. transaction.on_commit() registers a callback that runs only after the outer transaction commits, which is the right place for emails, task queuing and cache invalidation.

Full answer

A transaction makes several database changes behave as one. Paying a canteen bill might need two changes: subtract from the student's wallet and insert a payment row. If the second fails after the first succeeded, the data is wrong. A transaction prevents that.

Django defaults:

  • Autocommit: every query commits immediately unless you are inside atomic().
  • ATOMIC_REQUESTS = True (per database) wraps every view in a transaction. Simple, but it holds a transaction open for the whole request, including slow template rendering or API calls.

transaction.atomic() works as a decorator or a context manager:

python
with transaction.atomic():
    wallet.balance = F("balance") - 120
    wallet.save()
    Payment.objects.create(...)

If an exception leaves the block, Django rolls back. If the block ends normally, it commits.

Nesting: an inner atomic() creates a savepoint. If the inner block fails and you catch the exception outside it, only the inner work is undone and the outer transaction can continue. Do not catch database errors inside an atomic block and keep querying; wrap the risky part in its own inner atomic() instead.

transaction.on_commit(func) runs func after the outermost transaction commits, and never if it rolls back. Without it, a Celery task could start before the row it needs is visible, or a "payment received" email could go out for a payment that was rolled back. Outside any transaction the callback runs immediately. Django 5.0 added robust=True so one failing callback does not stop the others.

In tests, TestCase wraps each test in a transaction that never commits, so use self.captureOnCommitCallbacks(execute=True) to run on_commit callbacks.

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, transaction, IntegrityError
from django.db.models import F


class Wallet(models.Model):
    student = models.CharField(max_length=30, unique=True)
    balance = models.IntegerField()
    class Meta:
        app_label = "school"


class Payment(models.Model):
    student = models.CharField(max_length=30)
    amount = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Wallet)
    editor.create_model(Payment)

Wallet.objects.create(student="rohan", balance=500)
sent = []


def pay(student, amount, fail=False):
    with transaction.atomic():
        Wallet.objects.filter(student=student).update(balance=F("balance") - amount)
        Payment.objects.create(student=student, amount=amount)
        transaction.on_commit(lambda: sent.append(f"receipt {amount}"))
        if fail:
            raise RuntimeError("card machine offline")


pay("rohan", 120)
try:
    pay("rohan", 200, fail=True)
except RuntimeError:
    pass
print(Wallet.objects.get().balance, Payment.objects.count(), sent)

# Savepoint: the inner failure is undone, the outer work survives
with transaction.atomic():
    Payment.objects.create(student="rohan", amount=1)
    try:
        with transaction.atomic():
            Wallet.objects.create(student="rohan", balance=0)  # duplicate -> IntegrityError
    except IntegrityError:
        print("duplicate wallet rolled back to savepoint")
print(Payment.objects.count())

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): 380 1 ['receipt 120'] duplicate wallet rolled back to savepoint 2

Key points

  • Autocommit by default; atomic() groups changes
  • Exceptions inside atomic() roll back
  • Nested atomic() uses savepoints
  • on_commit callbacks run only after a successful commit
  • Avoid ATOMIC_REQUESTS for slow views

Common mistakes

  • Sending emails or queueing tasks inside a transaction without on_commit
  • Catching IntegrityError inside atomic() and continuing without an inner savepoint
  • Turning on ATOMIC_REQUESTS and holding transactions open during slow work
  • Testing on_commit logic in TestCase without captureOnCommitCallbacks

Follow-ups

  • What is the difference between atomic() and select_for_update()?
  • What isolation level does PostgreSQL use by default and why does it matter?
  • How would you make a payment handler idempotent?

Tips

  • Use a money example to show why atomicity matters
  • Explain savepoints with nested atomic()
  • Mention on_commit for side effects, it is a strong signal of real experience
28.django-0028Mediummid

In Django REST Framework, what is the difference between Serializer and ModelSerializer, and how does validation work?

A Serializer converts between Python objects and primitive data (JSON) with fields you declare; you write create() and update() yourself. ModelSerializer builds fields from a model and provides default create() and update(). Validation runs field checks, then validate_<field>() methods, then validate() for cross-field rules; call is_valid() before save(), and read serializer.errors when it fails.

Full answer

Serializers do two jobs in DRF:

  1. Serialisation: model instance to a dict that renders as JSON (serializer.data).
  2. Deserialisation: incoming JSON to validated Python data (serializer.validated_data), and optionally to a saved instance.

serializers.Serializer declares every field by hand, like forms.Form. Use it for payloads that do not map to one model, for example a "transfer fee credit" request.

serializers.ModelSerializer reads the model:

python
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ["id", "title", "copies"]
        read_only_fields = ["id"]

It infers field types, max_length, required (from blank/default) and unique validators, and gives you create() and update().

Validation order on is_valid():

  1. Each field converts and validates its value (to_internal_value and field validators).
  2. validate_<field>(self, value) for one-field rules; return the value.
  3. validate(self, attrs) for rules across fields; return attrs.
  4. Serializer-level validators such as UniqueTogetherValidator.

is_valid(raise_exception=True) raises ValidationError, which DRF turns into a 400 response.

Practical points:

  • Always list fields; avoid "__all__" in public APIs.
  • Use read_only=True for computed or server-set fields and write_only=True for secrets like passwords.
  • SerializerMethodField adds computed output.
  • Nested serializers are read-only by default; writable nesting needs your own create()/update().
  • save(owner=request.user) passes extra values into validated_data.
  • Serializer performance matters: nested serializers on a list can trigger N+1 queries, so pair them with select_related/prefetch_related in the view's queryset.
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
from rest_framework import serializers


class Book(models.Model):
    title = models.CharField(max_length=60)
    copies = models.PositiveIntegerField(default=1)
    shelf = models.CharField(max_length=5)
    class Meta:
        app_label = "school"


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


class BookSerializer(serializers.ModelSerializer):
    label = serializers.SerializerMethodField()

    class Meta:
        model = Book
        fields = ["id", "title", "copies", "shelf", "label"]
        read_only_fields = ["id"]

    def get_label(self, obj):
        return f"{obj.shelf}/{obj.title}"

    def validate_shelf(self, value):
        if not value[:1].isalpha():
            raise serializers.ValidationError("Shelf must start with a letter, like A1.")
        return value.upper()

    def validate(self, attrs):
        if attrs.get("copies", 1) > 50 and attrs.get("shelf", "").startswith("Z"):
            raise serializers.ValidationError("Shelf Z holds at most 50 copies.")
        return attrs


s = BookSerializer(data={"title": "Swami and Friends", "copies": 3, "shelf": "b2"})
print(s.is_valid(), s.validated_data)
book = s.save()
print(BookSerializer(book).data)

bad = BookSerializer(data={"title": "", "copies": -1, "shelf": "9X"})
print(bad.is_valid())
print({k: [str(e) for e in v] for k, v in bad.errors.items()})

upd = BookSerializer(book, data={"copies": 5}, partial=True)
upd.is_valid(raise_exception=True)
print(upd.save().copies)

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` (run here with DRF 3.16+). Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): True {'title': 'Swami and Friends', 'copies': 3, 'shelf': 'B2'} {'id': 1, 'title': 'Swami and Friends', 'copies': 3, 'shelf': 'B2', 'label': 'B2/Swami and Friends'} False {'title': ['This field may not be blank.'], 'copies': ['Ensure this value is greater than or equal to 0.'], 'shelf': ['Shelf must start with a letter, like A1.']} 5

Key points

  • Serializer = declare fields; ModelSerializer = fields from model + create/update
  • Order: field validation -> validate_<field> -> validate()
  • is_valid() before save(); errors on failure
  • read_only and write_only control direction
  • Nested serializers can cause N+1 queries

Common mistakes

  • Calling serializer.data or save() before is_valid()
  • Using fields = '__all__' and leaking internal fields
  • Forgetting to return the value from validate_<field>()
  • Nesting serializers in list endpoints without prefetching

Follow-ups

  • How do you make a nested serializer writable?
  • Where would you set the request user as owner?
  • How would you return different fields for list and detail views?

Tips

  • Compare with Django forms, the validation flow is similar
  • Name the three validation hooks in order
  • Mention N+1 queries in nested serializers
29.django-0029Mediummid

What are ViewSets and routers in Django REST Framework, and when would you use APIView or generic views instead?

A ViewSet groups the actions for one resource (list, create, retrieve, update, partial_update, destroy) in one class, and a router generates the URL patterns for them. ModelViewSet gives full CRUD from a queryset and serializer_class. Use @action for extra endpoints, generic views (ListCreateAPIView and friends) for fewer actions, and APIView when the endpoint does not fit the resource pattern.

Full answer

DRF has three layers of view abstraction:

  • APIView: like Django's View, with DRF request parsing, authentication, permissions, throttling and content negotiation. You write get(), post() yourself.
  • Generic views and mixins: ListAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView. You set queryset and serializer_class, and override hooks such as get_queryset() and perform_create().
  • ViewSets: one class with actions instead of HTTP methods. ModelViewSet gives list, create, retrieve, update, partial_update and destroy. ReadOnlyModelViewSet gives only list and retrieve.

A router maps actions to URLs:

python
router = DefaultRouter()
router.register("books", BookViewSet, basename="book")
urlpatterns = router.urls

This produces /books/ (GET list, POST create) and /books/{pk}/ (GET, PUT, PATCH, DELETE), with names like book-list and book-detail. DefaultRouter also adds an API root view.

Extra endpoints use @action:

python
@action(detail=True, methods=["post"])
def issue(self, request, pk=None): ...

which becomes POST /books/{pk}/issue/.

Hooks worth knowing:

  • get_queryset(): scope by user, add select_related.
  • get_serializer_class(): different serializers for list vs detail, or by self.action.
  • perform_create(serializer): serializer.save(owner=self.request.user).
  • get_permissions(): different permissions per action.

Choose ViewSets when a resource really is CRUD. When an endpoint is a command ("recalculate fees for March"), an APIView or a single @action is clearer than forcing it into CRUD.

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
from django.db.models import F
from django.urls import include, path
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.routers import DefaultRouter
from rest_framework.test import APIClient


class Book(models.Model):
    title = models.CharField(max_length=60)
    copies = models.PositiveIntegerField(default=1)
    class Meta:
        app_label = "school"


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


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ["id", "title", "copies"]


class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.order_by("id")
    serializer_class = BookSerializer
    authentication_classes = []
    permission_classes = []

    @action(detail=True, methods=["post"])
    def issue(self, request, pk=None):
        updated = Book.objects.filter(pk=pk, copies__gt=0).update(copies=F("copies") - 1)
        if not updated:
            return Response({"detail": "No copies left"}, status=409)
        return Response(BookSerializer(Book.objects.get(pk=pk)).data)


router = DefaultRouter()
router.register("books", BookViewSet, basename="book")
urlpatterns = [path("api/", include(router.urls))]
settings.ROOT_URLCONF = __name__

print(sorted({p.name for p in router.urls if p.name}))

c = APIClient()
print(c.post("/api/books/", {"title": "Kanthapura", "copies": 1}, format="json").json())
print(c.get("/api/books/").json())
print(c.post("/api/books/1/issue/").json())
r = c.post("/api/books/1/issue/")
print(r.status_code, r.json())
print(c.patch("/api/books/1/", {"copies": 4}, format="json").json())
print(c.delete("/api/books/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` (run here with DRF 3.16+). Authentication and permissions are switched off on this ViewSet only to keep the demo short; see the auth question for real settings. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['api-root', 'book-detail', 'book-issue', 'book-list'] {'id': 1, 'title': 'Kanthapura', 'copies': 1} [{'id': 1, 'title': 'Kanthapura', 'copies': 1}] {'id': 1, 'title': 'Kanthapura', 'copies': 0} 409 {'detail': 'No copies left'} {'id': 1, 'title': 'Kanthapura', 'copies': 4} 204

Key points

  • APIView < generic views < ViewSets in abstraction
  • ModelViewSet gives full CRUD; routers build URLs
  • @action adds custom endpoints
  • Override get_queryset, get_serializer_class, perform_create
  • Use APIView for endpoints that are commands, not resources

Common mistakes

  • Using ModelViewSet for endpoints that should not allow delete or update
  • Forgetting basename when the ViewSet has no queryset attribute
  • Putting user scoping in the serializer instead of get_queryset()
  • Creating a whole ViewSet for a single command-like endpoint

Follow-ups

  • How would you allow only list and create on a resource?
  • How do you use a different serializer for the list action?
  • What URL does @action(detail=False) produce?

Tips

  • Lay out the three abstraction levels
  • Show a custom @action with a real business reason
  • Mention get_queryset scoping for security
30.django-0030Mediummid

How do authentication and permissions work in Django REST Framework?

Authentication identifies the caller: DRF tries each class in authentication_classes (session, token, JWT via a package) and sets request.user and request.auth. Permissions then decide access: has_permission() runs for every request and has_object_permission() runs when get_object() is called. Failed authentication gives 401 (or 403 for schemes without a WWW-Authenticate header) and failed permission gives 403.

Full answer

DRF separates three checks that run in APIView.initial() before your handler:

  1. Authentication: who is calling?
  2. Permissions: may they do this?
  3. Throttling: are they calling too often?

Authentication classes (set globally in REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"] or per view):

  • SessionAuthentication: uses the Django session cookie; enforces CSRF for unsafe methods. Good for a browser front end on the same site.
  • TokenAuthentication: Authorization: Token <key>, keys stored in the authtoken table.
  • BasicAuthentication: mainly for testing.
  • JWT through djangorestframework-simplejwt: Authorization: Bearer <token>, no database lookup per request for the token itself.

Each class returns (user, auth) or None to let the next class try. If none succeed, request.user is AnonymousUser.

Permission classes:

  • AllowAny, IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly, DjangoModelPermissions.
  • Combine with &, |, ~.
  • Custom classes implement has_permission(request, view) and/or has_object_permission(request, view, obj).

Object permissions run only when the view calls get_object() (retrieve, update, destroy). They do not filter list results. For lists, filter the queryset in get_queryset().

Status codes: unauthenticated requests get 401 when the first authentication class provides a WWW-Authenticate header (Token, Basic), otherwise 403. Authenticated users without permission get 403.

Set secure defaults globally (IsAuthenticated) and open specific endpoints with AllowAny, rather than the reverse.

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", "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.core.management import call_command
from django.db import models, connection
from django.urls import path
from rest_framework import generics, permissions, serializers
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient

settings.PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
call_command("migrate", verbosity=0)
User = get_user_model()


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


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


class IsOwner(permissions.BasePermission):
    message = "You can only open your own notes."

    def has_object_permission(self, request, view, obj):
        return obj.owner_id == request.user.id


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


class NoteDetail(generics.RetrieveAPIView):
    queryset = Note.objects.all()
    serializer_class = NoteSerializer
    authentication_classes = [TokenAuthentication]
    permission_classes = [permissions.IsAuthenticated, IsOwner]


urlpatterns = [path("notes/<int:pk>/", NoteDetail.as_view())]
settings.ROOT_URLCONF = __name__

kavya = User.objects.create_user("kavya", password="x")
arun = User.objects.create_user("arun", password="x")
note = Note.objects.create(owner=kavya, text="Physics lab on Friday")

c = APIClient()
r = c.get(f"/notes/{note.pk}/")
print("no token:", r.status_code, r.headers.get("WWW-Authenticate"))

c.credentials(HTTP_AUTHORIZATION="Token " + Token.objects.create(user=arun).key)
print("other user:", c.get(f"/notes/{note.pk}/").status_code)

c.credentials(HTTP_AUTHORIZATION="Token " + Token.objects.create(user=kavya).key)
print("owner:", c.get(f"/notes/{note.pk}/").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` (run here with DRF 3.16+). Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): no token: 401 Token other user: 403 owner: {'id': 1, 'text': 'Physics lab on Friday'}

Key points

  • Authentication sets request.user; permissions decide access
  • Classes are tried in order; None means try the next
  • Object permissions run only via get_object()
  • Filter list endpoints in get_queryset()
  • Default to IsAuthenticated globally

Common mistakes

  • Relying on has_object_permission to protect list endpoints
  • Setting AllowAny as the global default
  • Mixing up 401 and 403
  • Using SessionAuthentication from a separate front-end domain and fighting CSRF instead of using tokens

Follow-ups

  • How would you let admins read every note but users only their own?
  • How do JWT access and refresh tokens work with simplejwt?
  • Where does throttling fit in the request cycle?

Tips

  • Separate authentication and authorisation clearly
  • Point out that object permissions do not filter lists
  • Explain when a 401 becomes a 403
31.django-0031Mediummid

What caching options does Django provide, and how do you choose between them?

Django has a cache framework with backends such as Redis, Memcached, local memory and database. You can cache whole views with @cache_page, template fragments with {% cache %}, or any value with the low-level API (cache.get, cache.set, cache.get_or_set). Choose by how much of the response is shared between users and how stale it may be, and plan invalidation from the start.

Full answer

Configure caches in the CACHES setting. Common backends:

  • django.core.cache.backends.redis.RedisCache (built in since Django 4.0) or memcached.PyMemcacheCache for production, shared across processes and servers.
  • locmem.LocMemCache: per process, good for development and tests.
  • db.DatabaseCache and filebased.FileBasedCache: rarely the best choice.
  • dummy.DummyCache: caches nothing, useful to switch caching off.

Levels of caching, from widest to narrowest:

  1. Per-site: UpdateCacheMiddleware and FetchFromCacheMiddleware. Caches every anonymous GET. Rarely right for apps with logged-in users.
  2. Per-view: @cache_page(60 * 15). Cache key includes the URL and headers listed in Vary. Safe for public pages, dangerous for personalised ones unless you vary on cookie.
  3. Template fragment: {% cache 600 sidebar request.user.id %} caches a slow part of a page.
  4. Low-level API: cache.get(key), cache.set(key, value, timeout), cache.get_or_set(key, callable, timeout), cache.delete(key), cache.incr(key). Best control; cache computed results such as "class average for 10A".

Invalidation strategies:

  • Time-based expiry (timeout). Simple, accepts some staleness.
  • Delete on write: when marks change, cache.delete(f"class-avg:{room_id}"). Do it in transaction.on_commit so readers do not repopulate the cache with old data before the commit.
  • Versioned keys: include a version or updated_at in the key so new data gets a new key.

Watch for cache stampedes: when a popular key expires, many requests recompute it at once. Mitigate with slightly random timeouts, a lock, or background refresh. Cache what is expensive and read often; caching cheap queries only adds complexity.

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.core.cache import cache
from django.db import models, connection
from django.db.models import Avg
from django.test.utils import CaptureQueriesContext

settings.CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}


class Mark(models.Model):
    room = models.CharField(max_length=5)
    score = models.IntegerField()
    class Meta:
        app_label = "school"


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

Mark.objects.bulk_create([Mark(room="10A", score=s) for s in (70, 80, 90)])


def class_average(room):
    return cache.get_or_set(
        f"class-avg:{room}",
        lambda: Mark.objects.filter(room=room).aggregate(a=Avg("score"))["a"],
        timeout=300,
    )


def add_mark(room, score):
    Mark.objects.create(room=room, score=score)
    cache.delete(f"class-avg:{room}")  # in real code: inside transaction.on_commit


with CaptureQueriesContext(connection) as ctx:
    print(class_average("10A"), class_average("10A"))
print("queries for two reads:", len(ctx.captured_queries))

add_mark("10A", 40)
print("after new mark:", class_average("10A"))

cache.set("visits", 0)
cache.incr("visits"); cache.incr("visits")
print("visits:", cache.get("visits"))

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): 80.0 80.0 queries for two reads: 1 after new mark: 70.0 visits: 2

Key points

  • Redis or Memcached in production; locmem for dev
  • Per-site, per-view, fragment and low-level caching
  • cache.get_or_set for computed values
  • Invalidate on write with on_commit, or use versioned keys
  • Watch for stampedes on hot keys

Common mistakes

  • Caching personalised pages with cache_page and showing one user's data to another
  • Using LocMemCache in production with several processes, so each has a different cache
  • Deleting the cache key before the transaction commits
  • Caching everything without measuring what is slow

Follow-ups

  • How would you prevent a cache stampede on a popular key?
  • How do you cache an API response that differs per user?
  • What is the Vary header and how does cache_page use it?

Tips

  • Name the four caching levels
  • Always talk about invalidation, not just storing
  • Mention Redis as the common production backend
32.django-0032Mediummid

What are custom managers and custom QuerySet methods in Django, and why use QuerySet.as_manager()?

A manager is the interface for table-level queries (Model.objects). Adding methods to a custom QuerySet class and exposing it with QuerySet.as_manager() or Manager.from_queryset() gives chainable, reusable filters such as Book.objects.available().by_author(...). Overriding get_queryset() on a manager changes the default rows it returns, which is how soft-delete filters are often built.

Full answer

Book.objects is a Manager. It hands out QuerySets. When the same filter appears in many views, for example "books that are in stock and not lost", put it on the model layer rather than repeating filter(copies__gt=0, lost=False) everywhere.

Two places to add logic:

  • Custom QuerySet methods: chainable, because each returns a QuerySet.
  • Custom Manager methods: table-level helpers, such as a create_student() that sets defaults.

The usual pattern puts methods on a QuerySet and exposes them through the manager:

python
class BookQuerySet(models.QuerySet):
    def available(self):
        return self.filter(copies__gt=0, lost=False)
    def by_author(self, name):
        return self.filter(author__iexact=name)

class Book(models.Model):
    ...
    objects = BookQuerySet.as_manager()

Now Book.objects.available().by_author("Ruskin Bond") chains in any order.

Manager.from_queryset(BookQuerySet) is used when you also need custom manager-only methods or want to override get_queryset().

Changing default rows: a manager whose get_queryset() filters out soft-deleted records hides them everywhere. Keep a second, unfiltered manager (all_objects = models.Manager()), and know that Django uses Meta.base_manager_name (the plain base manager by default) for related object access, so a default-manager filter does not apply to loan.book.

Rules:

  • The first manager defined on the model is the default manager unless Meta.default_manager_name says otherwise.
  • Keep QuerySet methods about selecting rows. Complex business workflows (issue a book, send a notice) fit better in service functions.
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


class BookQuerySet(models.QuerySet):
    def available(self):
        return self.filter(copies__gt=0, lost=False)

    def by_author(self, name):
        return self.filter(author__iexact=name)


class ActiveManager(models.Manager.from_queryset(BookQuerySet)):
    def get_queryset(self):
        return super().get_queryset().filter(deleted=False)


class Book(models.Model):
    title = models.CharField(max_length=60)
    author = models.CharField(max_length=40)
    copies = models.PositiveIntegerField(default=1)
    lost = models.BooleanField(default=False)
    deleted = models.BooleanField(default=False)

    objects = ActiveManager()          # default: hides soft-deleted rows
    all_objects = models.Manager()     # everything

    class Meta:
        app_label = "school"


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

Book.all_objects.bulk_create([
    Book(title="The Blue Umbrella", author="Ruskin Bond", copies=2),
    Book(title="Rusty Runs Away", author="Ruskin Bond", copies=0),
    Book(title="The Room on the Roof", author="Ruskin Bond", lost=True),
    Book(title="Delhi Is Not Far", author="Ruskin Bond", deleted=True),
    Book(title="Malgudi Days", author="R. K. Narayan"),
])

print(list(Book.objects.available().by_author("ruskin bond").values_list("title", flat=True)))
print(list(Book.objects.by_author("Ruskin Bond").available().values_list("title", flat=True)))
print(Book.objects.count(), Book.all_objects.count())

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): ['The Blue Umbrella'] ['The Blue Umbrella'] 4 5

Key points

  • Managers create QuerySets; QuerySet methods chain
  • QuerySet.as_manager() exposes chainable methods on objects
  • Override get_queryset() to change default rows
  • Keep an unfiltered manager alongside a filtered one
  • Related access uses the base manager

Common mistakes

  • Putting reusable filters on the manager only, so they cannot be chained
  • Filtering the default manager and being surprised that related access still shows hidden rows
  • Accidentally making a filtered manager the default and breaking the admin or dumpdata
  • Moving whole business workflows into QuerySet methods

Follow-ups

  • How would you build soft delete across the whole project?
  • What is the base manager used for?
  • How do custom managers behave in migrations (use_in_migrations)?

Tips

  • Show a chain in both orders to prove the methods compose
  • Mention the default manager rule
  • Bring up soft delete as a real use case
33.django-0033Mediummid

How do you define database indexes and constraints in Django models, and why put rules in the database?

Use Meta.indexes with models.Index for query speed, and Meta.constraints with UniqueConstraint and CheckConstraint for data rules. Database constraints protect data even when code bypasses validation, for example with update(), bulk_create() or another service writing to the same tables. Since Django 4.1, model validation also checks constraints during full_clean().

Full answer

Indexes make reads faster. Constraints keep data correct. Both belong in Meta and are created by migrations.

Indexes:

  • db_index=True on a field for a simple single-column index (ForeignKeys get one automatically).
  • models.Index(fields=["room", "-exam_date"], name="mark_room_date_idx") for multi-column indexes. Column order matters: this index helps WHERE room = ... and WHERE room = ... ORDER BY exam_date DESC, not WHERE exam_date = ... alone.
  • condition=Q(...) makes a partial index on PostgreSQL and SQLite, for example only rows where is_active=True.
  • Expression indexes, such as Index(Lower("email"), name=...), for case-insensitive lookups.

Constraints:

  • UniqueConstraint(fields=["student", "subject", "exam"], name="one_mark_per_exam"). Supports condition= (unique only for some rows) and, from Django 5.0, nulls_distinct on PostgreSQL 15+.
  • CheckConstraint(condition=Q(score__gte=0) & Q(score__lte=100), name="score_0_100"). Django 5.1 renamed the argument from check= to condition=; the old name was deprecated in 5.1 and removed in 6.0.
  • unique_together still works but UniqueConstraint is preferred.

Why the database and not only Python validation? Validation in forms and serializers can be skipped by update(), bulk_create(), raw SQL, scripts and other services. Two requests can also pass a Python uniqueness check at the same time and both insert. A database constraint is the only check that closes that race.

Since Django 4.1, full_clean() validates constraints too, so forms show a friendly error before the database raises IntegrityError.

Cost: every index slows writes and uses disk. Add indexes for queries you actually run, confirmed with EXPLAIN.

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.core.exceptions import ValidationError
from django.db import models, connection, IntegrityError, transaction
from django.db.models import Q


class Mark(models.Model):
    student = models.CharField(max_length=30)
    subject = models.CharField(max_length=20)
    exam = models.CharField(max_length=10)
    score = models.IntegerField()

    class Meta:
        app_label = "school"
        indexes = [models.Index(fields=["subject", "-score"], name="mark_subject_score_idx")]
        constraints = [
            models.UniqueConstraint(fields=["student", "subject", "exam"], name="one_mark_per_exam"),
            models.CheckConstraint(condition=Q(score__gte=0) & Q(score__lte=100), name="score_0_100"),
        ]


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

Mark.objects.create(student="zoya", subject="Maths", exam="mid", score=88)

for label, kwargs in [("duplicate", dict(student="zoya", subject="Maths", exam="mid", score=90)),
                      ("score 120", dict(student="zoya", subject="Maths", exam="final", score=120))]:
    try:
        with transaction.atomic():
            Mark.objects.bulk_create([Mark(**kwargs)])  # skips Python validation
    except IntegrityError as e:
        print(label, "-> IntegrityError:", str(e).split(":")[0])

try:
    Mark(student="zoya", subject="Maths", exam="final", score=-5).full_clean()
except ValidationError as e:
    print("full_clean:", e.messages)

with connection.cursor() as cur:
    idx = connection.introspection.get_constraints(cur, Mark._meta.db_table)
print(sorted(name for name, info in idx.items() if info["index"] and not info["primary_key"]))

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): duplicate -> IntegrityError: UNIQUE constraint failed score 120 -> IntegrityError: CHECK constraint failed full_clean: ['Constraint “score_0_100” is violated.'] ['mark_subject_score_idx']

Key points

  • Meta.indexes for speed; Meta.constraints for correctness
  • Multi-column index order matters
  • CheckConstraint uses condition= since Django 5.1; check= is gone in 6.0
  • Database constraints close race conditions Python checks cannot
  • full_clean() validates constraints since Django 4.1

Common mistakes

  • Relying only on form validation for uniqueness, which fails under concurrent requests
  • Using check= instead of condition= (deprecated in 5.1, removed in 6.0)
  • Adding indexes on every column and slowing every write
  • Ordering multi-column index fields without thinking about the queries

Follow-ups

  • How would you enforce 'only one active enrolment per student'?
  • How do you add an index to a huge PostgreSQL table without locking writes?
  • What does EXPLAIN tell you about whether an index is used?

Tips

  • Separate the purpose: indexes for speed, constraints for correctness
  • Explain the race condition that only a database constraint solves
  • Mention the Django 5.1 check= to condition= rename
34.django-0034Mediummid

How do you write a custom Django management command, and what are good practices for it?

Create app/management/commands/<name>.py with a Command class that subclasses BaseCommand, define add_arguments() with argparse options, and put the work in handle(). Run it with python manage.py <name>. Write output through self.stdout and self.style, raise CommandError for failures, support a --dry-run option for risky jobs, and test it with call_command().

Full answer

Management commands are scripts that run with the project's settings, models and apps loaded. Built-in ones include migrate, createsuperuser and shell. Custom commands suit jobs such as sending fee reminders, importing a CSV of new admissions or cleaning old sessions.

File layout: attendance/management/commands/mark_absent.py (both management/ and commands/ need __init__.py). The file name becomes the command name.

python
class Command(BaseCommand):
    help = "Mark students absent who did not check in"

    def add_arguments(self, parser):
        parser.add_argument("date")
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        ...

Good practices:

  • Use self.stdout.write() and self.stderr.write() instead of print, so tests and call_command can capture output. self.style.SUCCESS(...) and self.style.ERROR(...) add colour in terminals.
  • Raise CommandError("message") for expected failures; it prints the message and exits with a non-zero code, which cron and CI notice.
  • Add --dry-run for anything that changes or deletes data.
  • Process large data sets in batches with iterator() and wrap each batch in transaction.atomic().
  • Make the command safe to run twice (idempotent), because schedulers retry.
  • Respect --verbosity (options["verbosity"]).
  • Test with call_command("mark_absent", "2026-12-04", dry_run=True, stdout=StringIO()).

Scheduling is outside Django: cron, Kubernetes CronJobs, systemd timers or a task queue scheduler such as Celery beat run the command.

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 io import StringIO
from django.core.management.base import BaseCommand, CommandError
from django.db import models, connection


class Attendance(models.Model):
    roll_no = models.IntegerField()
    date = models.DateField()
    status = models.CharField(max_length=10, default="unknown")
    class Meta:
        app_label = "school"


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

for r in (1, 2, 3):
    Attendance.objects.create(roll_no=r, date="2026-12-04", status="present" if r == 2 else "unknown")


class Command(BaseCommand):
    help = "Mark students absent who have no check-in for the given date"

    def add_arguments(self, parser):
        parser.add_argument("date")
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        qs = Attendance.objects.filter(date=options["date"], status="unknown")
        if not Attendance.objects.filter(date=options["date"]).exists():
            raise CommandError(f"No attendance sheet for {options['date']}")
        if options["dry_run"]:
            self.stdout.write(f"Would mark {qs.count()} students absent")
            return
        changed = qs.update(status="absent")
        self.stdout.write(self.style.SUCCESS(f"Marked {changed} students absent"))


def run(*argv):
    out = StringIO()
    cmd = Command(stdout=out)
    parser = cmd.create_parser("manage.py", "mark_absent")
    options = vars(parser.parse_args(argv))
    cmd.execute(**options)
    return out.getvalue().strip()


print(run("2026-12-04", "--dry-run"))
print(run("2026-12-04", "--no-color"))
print(run("2026-12-04", "--no-color"))  # safe to run again
try:
    run("2026-12-05")
except CommandError as e:
    print("CommandError:", e)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. In a project the class lives in attendance/management/commands/mark_absent.py and you call it with call_command or manage.py; here it is parsed and executed directly. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): Would mark 2 students absent Marked 2 students absent Marked 0 students absent CommandError: No attendance sheet for 2026-12-05

Key points

  • Path: app/management/commands/<name>.py with class Command(BaseCommand)
  • add_arguments() for options, handle() for the work
  • self.stdout and CommandError instead of print and sys.exit
  • --dry-run and idempotency for data-changing jobs
  • Test with call_command()

Common mistakes

  • Using print() so output cannot be captured in tests
  • Calling sys.exit() instead of raising CommandError
  • Loading millions of rows into memory at once
  • Writing commands that double-apply changes when re-run

Follow-ups

  • How would you schedule this command in production?
  • How do you test a command that reads a CSV file?
  • When would a task queue be better than a management command?

Tips

  • Show the file path, it is a common gotcha
  • Mention dry-run and idempotency
  • Talk about how the command is scheduled and monitored
35.django-0035Hardsenior

How do async views and the async ORM work in Django 5.x, and what are their limits?

An async view is an async def function (or a class with async handlers) that Django runs on the event loop under ASGI. The ORM offers async methods such as aget(), acreate(), acount(), aexists() and async for over QuerySets, but under the hood most database calls still run in a thread through sync_to_async because database drivers used by Django are synchronous. Async views pay off for I/O such as calling external APIs concurrently, not for CPU work or plain ORM pages.

Full answer

Django has supported async views since 3.1 and an async ORM interface since 4.1. In Django 5.x:

  • A view written as async def runs on the event loop when served by an ASGI server (Uvicorn, Daphne, Hypercorn). Under WSGI, Django runs it in a one-off event loop per request, which gives no concurrency benefit.
  • Class-based views can define async def get(); all handlers on the class must be either sync or async.
  • QuerySet methods have a-prefixed versions: aget, afirst, acreate, aupdate, adelete, acount, aexists, aaggregate, ain_bulk, and async for obj in qs. Model instances have asave, adelete, arefresh_from_db.
  • Django 5.0 added aget_object_or_404, async auth functions such as aauthenticate() and alogin(), and async signal dispatch (asend()).

The limit: Django's database backends are still synchronous. Async ORM calls are wrapped with sync_to_async and run in a thread pool, one at a time per connection. So an async view that only runs ORM queries is not faster than a sync view; it can even be slightly slower because of thread hops.

Where async helps: a view that waits on several slow outside services. Calling three APIs with httpx.AsyncClient and asyncio.gather takes about as long as the slowest one, instead of the sum.

Rules:

  • Never call blocking code (requests, time.sleep, sync ORM) directly in an async view. Django raises SynchronousOnlyOperation for sync ORM calls in an async context. Wrap legacy code with sync_to_async.
  • Transactions: transaction.atomic() does not support async yet; put transactional work in a sync function and call it with sync_to_async.
  • Sync middleware in the stack makes Django switch threads for each request, eating the gain. Check that middleware is async-capable.
  • Accessing lazy relations (book.author) in async code triggers a sync query and raises; use select_related or await sync_to_async(...).
python
import sys
import tempfile
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": tempfile.mkdtemp() + "/school.sqlite3"}},
)
django.setup()

import asyncio
import time

from asgiref.sync import sync_to_async
from django.core.exceptions import SynchronousOnlyOperation
from django.db import models, connection
from django.http import JsonResponse
from django.test import AsyncRequestFactory


class Student(models.Model):
    name = models.CharField(max_length=40)
    marks = models.IntegerField()
    class Meta:
        app_label = "school"


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


async def fetch_service(name, delay):
    await asyncio.sleep(delay)       # stands in for an httpx.AsyncClient call
    return name


async def dashboard(request):
    count = await Student.objects.filter(marks__gte=40).acount()
    names = [s.name async for s in Student.objects.order_by("name")]
    start = time.perf_counter()
    services = await asyncio.gather(fetch_service("fees", 0.3), fetch_service("library", 0.3),
                                    fetch_service("hostel", 0.3))
    took = time.perf_counter() - start
    return JsonResponse({"passed": count, "names": names, "services": services,
                         "concurrent": took < 0.6})


async def main():
    await Student.objects.acreate(name="Sneha", marks=72)
    await Student.objects.acreate(name="Vikram", marks=35)
    response = await dashboard(AsyncRequestFactory().get("/dashboard/"))
    print(response.content.decode())
    try:
        Student.objects.count()      # sync ORM call inside async code
    except SynchronousOnlyOperation:
        print("sync ORM call blocked inside the event loop")
    print(await sync_to_async(Student.objects.count)())


asyncio.run(main())

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 three services are simulated with asyncio.sleep; real code would use httpx.AsyncClient. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {"passed": 1, "names": ["Sneha", "Vikram"], "services": ["fees", "library", "hostel"], "concurrent": true} sync ORM call blocked inside the event loop 2

Key points

  • async def views run on the event loop under ASGI
  • Async ORM methods use the a- prefix and async for
  • Database calls still run in threads; no speedup for ORM-only views
  • Gain comes from concurrent external I/O
  • Sync ORM in async code raises SynchronousOnlyOperation; atomic() is sync only

Common mistakes

  • Expecting async views full of ORM queries to be faster than sync views
  • Calling requests or time.sleep inside async def and blocking the event loop
  • Running async views under WSGI and expecting concurrency
  • Using transaction.atomic() directly in async code
  • Leaving sync-only middleware in an ASGI stack

Follow-ups

  • Why is the async ORM still thread-based in Django 5.x?
  • How would you call a legacy sync function from an async view safely?
  • When would you choose FastAPI instead of async Django?

Tips

  • Say plainly where async helps and where it does not
  • Name SynchronousOnlyOperation and sync_to_async
  • Mention ASGI as a requirement for real concurrency
36.django-0036Hardsenior

How do you deploy Django in production? Compare WSGI and ASGI, and explain the role of Gunicorn, Uvicorn and a reverse proxy.

WSGI is the synchronous Python server interface; ASGI is its async successor that also supports WebSockets and long-lived connections. A typical setup runs Gunicorn with several worker processes (sync workers for WSGI, or Uvicorn workers for ASGI) behind Nginx or a cloud load balancer that terminates TLS, serves static files or forwards to a CDN, and buffers slow clients. Size workers from CPU cores and measure.

Full answer

Django exposes two entry points: project/wsgi.py (application = get_wsgi_application()) and project/asgi.py (get_asgi_application()).

WSGI (Web Server Gateway Interface) is one request in, one response out, synchronous. It is mature and simple. Use it when the app is fully sync, which most Django apps still are.

ASGI (Asynchronous Server Gateway Interface) supports async def views, WebSockets (with Django Channels), Server-Sent Events and long polling. Use it when you need these or want concurrent outbound I/O in views.

Process layout in production:

  • A reverse proxy or load balancer (Nginx, a cloud load balancer) terminates HTTPS, enforces body size limits, buffers slow clients and forwards to the app servers. Configure Django to trust its forwarded headers: SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https"), and only when the proxy sets that header itself.
  • Gunicorn manages worker processes, restarts crashed workers and recycles them (--max-requests). For WSGI: gunicorn project.wsgi -w 4. For ASGI: gunicorn project.asgi -k uvicorn_worker.UvicornWorker -w 4, or Uvicorn alone with --workers.
  • A common starting point is workers = 2 x CPU cores + 1 for sync workers, then tune with load tests. Threads (--threads) help when views wait on I/O.
  • Static files: collectstatic to a CDN or object storage, or WhiteNoise.
  • Background work in a separate worker process (Celery, RQ, or Django 6.0's tasks framework with a backend).

Release checklist: run manage.py check --deploy, run migrations as a separate step before switching traffic, keep migrations backward compatible so old and new code can run together during a rolling deploy, add a health check URL, and send logs to stdout for the platform to collect.

Containers: one process type per container (web, worker, scheduler), configuration from environment variables, and a non-root user.

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 asyncio

import httpx
from django.core.asgi import get_asgi_application
from django.core.wsgi import get_wsgi_application
from django.http import JsonResponse
from django.urls import path


def health(request):
    return JsonResponse({"status": "ok", "scheme": request.scheme})


urlpatterns = [path("healthz/", health)]
settings.ROOT_URLCONF = __name__
settings.ALLOWED_HOSTS = ["api.example.edu"]
settings.SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

wsgi_app = get_wsgi_application()   # what "gunicorn project.wsgi" loads
asgi_app = get_asgi_application()   # what "uvicorn project.asgi:application" loads

with httpx.Client(transport=httpx.WSGITransport(app=wsgi_app), base_url="http://api.example.edu") as c:
    print("WSGI:", c.get("/healthz/").json())


async def call_asgi():
    transport = httpx.ASGITransport(app=asgi_app)
    async with httpx.AsyncClient(transport=transport, base_url="http://api.example.edu") as c:
        r = await c.get("/healthz/", headers={"X-Forwarded-Proto": "https"})
        print("ASGI behind TLS proxy:", r.json())

asyncio.run(call_asgi())

# Typical commands (not run here):
#   gunicorn project.wsgi:application --workers 5 --bind 0.0.0.0:8000 --max-requests 2000
#   gunicorn project.asgi:application -k uvicorn_worker.UvicornWorker --workers 5

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. It loads the same WSGI and ASGI application objects a production server would load and calls them in-process with httpx; the Gunicorn commands are shown as comments and were not run. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3, gunicorn 27.0.1, uvicorn-worker 0.4.0): WSGI: {'status': 'ok', 'scheme': 'http'} ASGI behind TLS proxy: {'status': 'ok', 'scheme': 'https'}

Key points

  • WSGI = sync; ASGI = async, WebSockets, long-lived connections
  • Reverse proxy terminates TLS and buffers clients
  • Gunicorn manages workers; Uvicorn workers for ASGI
  • Start with about 2 x cores + 1 workers and load test
  • Run migrations as a separate, backward-compatible release step

Common mistakes

  • Running manage.py runserver in production
  • Setting SECURE_PROXY_SSL_HEADER when the proxy does not strip client-supplied headers
  • Running migrations inside every web container at startup and racing each other
  • Choosing ASGI for a fully sync app and adding thread-switch overhead

Follow-ups

  • How would you do a zero-downtime deploy with a schema change?
  • How do you choose the number of Gunicorn workers and threads?
  • What changes when you add WebSockets with Django Channels?

Tips

  • Draw the chain: client, proxy, app server, workers, database
  • Explain when ASGI is worth it
  • Mention backward-compatible migrations during rolling deploys
37.django-0037Hardsenior

How do you optimise heavy Django ORM queries? Explain only(), defer(), values(), iterator() and explain().

Load less and load smarter. only() and defer() limit columns while still returning model instances; values() and values_list() return dicts or tuples and skip model creation; iterator() streams rows in chunks instead of caching the whole result; exists(), count() and aggregates push work to the database; explain() shows the query plan so you can confirm index use. Measure first, then fix the biggest query.

Full answer

Slow ORM code usually has one of four causes: too many queries (N+1), too much data per query, too many rows held in memory, or a query the database cannot answer efficiently. Fix the measured problem, not a guessed one.

Load fewer columns:

  • only("id", "name") loads just those fields; accessing another field triggers a query per object, so use it only when you know what the code touches.
  • defer("biography") skips a large column such as a long TextField.
  • values("name", "marks") returns dicts and values_list("name", flat=True) returns plain values. No model instances are built, which is much cheaper for reports and exports. You lose model methods.

Handle many rows:

  • A normal QuerySet caches every row it loads. For 2 million attendance rows, for a in qs.iterator(chunk_size=2000) streams results and keeps memory flat. Since Django 4.1, prefetch_related works with iterator() when you pass chunk_size.
  • Batch writes with bulk_create / bulk_update, and use update() / delete() on a QuerySet instead of looping.

Let the database work:

  • exists() instead of if qs: when you need a yes/no answer.
  • count() instead of len(qs).
  • aggregate() / annotate() instead of summing in Python.
  • Subquery, OuterRef and Exists for "latest mark per student" style questions in one query.

Check the plan:

  • print(qs.query) shows SQL; qs.explain() (with analyze=True on PostgreSQL) shows whether an index is used.
  • Add indexes that match real filters and orderings.

Watch out for: order_by("?") (random ordering scans the whole table), OFFSET pagination deep into big tables (prefer keyset pagination), and distinct() on wide rows.

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 tracemalloc
from django.db import models, connection
from django.db.models import Exists, OuterRef, Subquery


class Student(models.Model):
    name = models.CharField(max_length=40)
    biography = models.TextField()
    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    score = models.IntegerField()
    exam_no = models.IntegerField()
    class Meta:
        app_label = "school"
        indexes = [models.Index(fields=["student", "-exam_no"], name="mark_student_exam_idx")]


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

Student.objects.bulk_create([Student(name=f"S{i:05d}", biography="x" * 2000) for i in range(5000)])
Mark.objects.bulk_create([Mark(student_id=i % 5000 + 1, score=(i * 7) % 101, exam_no=i // 5000)
                          for i in range(15000)])


def peak_kb(fn):
    tracemalloc.start()
    fn()
    peak = tracemalloc.get_traced_memory()[1]
    tracemalloc.stop()
    return peak // 1024

full = peak_kb(lambda: [s.name for s in Student.objects.all()])
slim = peak_kb(lambda: list(Student.objects.values_list("name", flat=True)))
streamed = peak_kb(lambda: [s.name for s in Student.objects.only("name").iterator(chunk_size=500)])
print("values_list uses less memory than full rows:", slim < full)
print("only()+iterator() uses less memory than full rows:", streamed < full)

latest = Mark.objects.filter(student=OuterRef("pk")).order_by("-exam_no")
qs = (Student.objects
      .annotate(latest_score=Subquery(latest.values("score")[:1]))
      .filter(Exists(Mark.objects.filter(student=OuterRef("pk"), score=100)))
      .order_by("name")
      .values("name", "latest_score")[:3])
print(list(qs))
print("index used:", "mark_student_exam_idx" in Mark.objects.filter(student_id=1).order_by("-exam_no").explain())

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. Memory numbers vary by machine, so the script prints comparisons instead of raw kilobytes. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): values_list uses less memory than full rows: True only()+iterator() uses less memory than full rows: True [{'name': 'S00021', 'latest_score': 53}, {'name': 'S00071', 'latest_score': 100}, {'name': 'S00072', 'latest_score': 6}] index used: True

Key points

  • only/defer limit columns but keep instances
  • values/values_list skip model creation
  • iterator(chunk_size=...) streams without caching
  • Push counting and summing into SQL
  • Use explain() to confirm index use

Common mistakes

  • Using only() and then touching deferred fields in a loop (one query per object)
  • Loading full model instances for a CSV export of two columns
  • Iterating millions of rows without iterator() and running out of memory
  • Adding indexes without checking the plan with explain()

Follow-ups

  • How would you get each student's latest mark in one query?
  • Why is OFFSET pagination slow on large tables, and what is keyset pagination?
  • When does iterator() not help on your database?

Tips

  • Start with 'measure first' and name the tools
  • Group fixes into columns, rows, and work pushed to SQL
  • Mention Subquery/Exists for per-row lookups
38.django-0038Hardsenior

What does select_for_update() do in Django, and how do nowait and skip_locked change it?

select_for_update() adds SELECT ... FOR UPDATE so the selected rows are locked until the surrounding transaction ends; other transactions that try to lock or update them wait. It must run inside transaction.atomic(). nowait=True raises an error instead of waiting, skip_locked=True skips rows already locked (useful for job queues), and of=(...) limits which joined tables are locked. SQLite ignores it, so test on the real database.

Full answer

F() updates solve simple counters, but some logic must read, decide, and then write. For example, approving a hostel room request: read the room, check that beds are free, then assign. Two admins doing this at once could both see one free bed and both assign it.

Pessimistic locking stops that:

python
with transaction.atomic():
    room = Room.objects.select_for_update().get(pk=room_id)
    if room.free_beds == 0:
        raise NoBedsLeft
    room.free_beds -= 1
    room.save(update_fields=["free_beds"])

The second transaction blocks on the SELECT ... FOR UPDATE until the first commits, then reads the updated value.

Rules and options:

  • It must be inside atomic(). Evaluating it in autocommit mode raises TransactionManagementError on databases that support it.
  • nowait=True fails immediately with DatabaseError if the row is locked. Good for user-facing actions where waiting is worse than a "try again" message.
  • skip_locked=True returns only unlocked rows. This is how several workers can take jobs from one table without picking the same job.
  • of=("self",) locks only the main table when you also select_related other tables. On PostgreSQL, no_key=True takes a weaker lock that does not block inserts referencing the row.
  • Support varies: PostgreSQL and Oracle support all options; MySQL 8 supports nowait and skip_locked; SQLite ignores select_for_update entirely.

Costs: locks reduce concurrency and can deadlock if two transactions lock rows in different orders. Lock in a consistent order (for example by primary key), keep the transaction short, and never call slow external services while holding a lock.

The alternative is optimistic locking: a version column, update(..., version=F("version") + 1) filtered on the old version, and retry if zero rows changed. It suits low-contention data.

python
import os
import sys
import types

import django
from django.conf import settings

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

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

import threading
import time

from django.db import connection, connections, models, transaction, DatabaseError
from django.db.transaction import TransactionManagementError


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


with connection.cursor() as cur:
    cur.execute("DROP TABLE IF EXISTS school_room")
with connection.schema_editor() as editor:
    editor.create_model(Room)
Room.objects.create(name="H-101", free_beds=1)

try:
    list(Room.objects.select_for_update())
except TransactionManagementError:
    print("select_for_update outside atomic() is an error")

results = []


def assign_bed(who, hold):
    try:
        with transaction.atomic():
            room = Room.objects.select_for_update().get(name="H-101")
            time.sleep(hold)
            if room.free_beds == 0:
                results.append(f"{who}: no beds left")
                return
            room.free_beds -= 1
            room.save(update_fields=["free_beds"])
            results.append(f"{who}: got the bed")
    finally:
        connections.close_all()


t1 = threading.Thread(target=assign_bed, args=("admin-1", 0.5))
t2 = threading.Thread(target=assign_bed, args=("admin-2", 0))
t1.start(); time.sleep(0.1); t2.start()
t1.join(); t2.join()
print(results)


def try_nowait():
    try:
        with transaction.atomic():
            Room.objects.select_for_update(nowait=True).get(name="H-101")
            results.append("nowait: locked it")
    except DatabaseError:
        results.append("nowait: row busy, failing fast")
    finally:
        connections.close_all()


results.clear()
with transaction.atomic():
    Room.objects.select_for_update().get(name="H-101")
    t = threading.Thread(target=try_nowait)
    t.start(); t.join()
    with connections["default"].cursor():
        pass
print(results)
print(Room.objects.get(name="H-101").free_beds)

Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. Ran on PostgreSQL 17 with two threads to show the second transaction waiting for the first. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): select_for_update outside atomic() is an error ['admin-1: got the bed', 'admin-2: no beds left'] ['nowait: row busy, failing fast'] 0

Key points

  • Locks selected rows until the transaction ends
  • Must run inside transaction.atomic()
  • nowait fails fast; skip_locked skips locked rows
  • SQLite ignores it; test on PostgreSQL or MySQL
  • Keep locked transactions short and lock in a consistent order

Common mistakes

  • Calling select_for_update() outside a transaction
  • Testing locking code on SQLite, where it silently does nothing
  • Holding the lock while calling a payment gateway or sending email
  • Locking rows in different orders in different code paths and causing deadlocks

Follow-ups

  • How would you build a job queue table that several workers read from?
  • Compare optimistic and pessimistic locking
  • What does of=('self',) change when using select_related?

Tips

  • Use a read-decide-write example where F() is not enough
  • Know nowait and skip_locked and give a use case for each
  • Mention database support differences, especially SQLite
39.django-0039Hardsenior

How do you run Django migrations on a large production table without downtime?

Make every migration backward compatible with the code that is still running, and split risky changes into steps across releases: add nullable columns or columns with a database default, backfill in batches, then add NOT NULL or constraints; create indexes concurrently on PostgreSQL; remove columns only after no code reads them, using SeparateDatabaseAndState when needed. Review the SQL with sqlmigrate and set lock timeouts.

Full answer

During a rolling deploy, old and new versions of the code run at the same time against one database. A migration is safe only if both versions work with the schema before and after it. Locks are the other danger: some ALTER TABLE statements take an exclusive lock, and on a busy 50-million-row table even a short wait queues every other query behind it.

Patterns for common changes:

Adding a column

  1. Add it nullable, or with db_default (Django 5.0+) so the database supplies the value. On PostgreSQL 11+, adding a column with a constant default is a metadata-only change and fast. A Python-side default= alone is applied by Django during the migration and then dropped from the database, which is not the same thing.
  2. Deploy code that writes the new column.
  3. Backfill old rows in batches (a data migration or a management command with small transactions).
  4. In a later release, make it NOT NULL or add constraints. On PostgreSQL, add a CHECK constraint as NOT VALID and validate it separately to avoid a long lock.

Adding an index

  • Use AddIndexConcurrently from django.contrib.postgres.operations in a migration with atomic = False. It does not block writes.

Renaming or removing a column

  • Never rename in one step. Add the new column, write both, backfill, switch reads, stop writing the old one, then drop it later.
  • To drop a field: first remove it from the model but keep it in the database using SeparateDatabaseAndState (or make it nullable so old code inserts still work), deploy, then drop the column in a later release.

Process habits

  • python manage.py sqlmigrate app 0042 to read the SQL before release.
  • Set lock_timeout (and statement_timeout) for the migration session so it fails fast instead of queuing traffic.
  • Run migrations once, as a separate release step, not in every container's start command.
  • Tools such as django-pg-zero-downtime-migrations or linters like django-migration-linter catch unsafe operations in CI.
python
import os
import sys
import types

import django
from django.conf import settings

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

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

from django.contrib.postgres.operations import AddIndexConcurrently
from django.db import connection, migrations, models
from django.db.migrations.state import ProjectState
from django.db.models.functions import Now


def sql_for(operations, state, atomic=True):
    """Return the SQL Django would run for these operations (like sqlmigrate)."""
    with connection.schema_editor(collect_sql=True, atomic=atomic) as editor:
        for op in operations:
            new_state = state.clone()
            op.state_forwards("school", new_state)
            op.database_forwards("school", editor, state, new_state)
            state = new_state
    return [s for s in editor.collected_sql if not s.startswith("--")], state


state = ProjectState()
create = [migrations.CreateModel("Attendance", [
    ("id", models.BigAutoField(primary_key=True)),
    ("roll_no", models.IntegerField()),
])]
_, state = sql_for(create, state)

step1 = [migrations.AddField("attendance", "source",
                             models.CharField(max_length=10, db_default="manual"))]
sql, state = sql_for(step1, state)
print("Step 1, add column with a database default:")
print(" ", sql[0])

step2 = [AddIndexConcurrently("attendance",
                              models.Index(fields=["source"], name="att_source_idx"))]
sql, state = sql_for(step2, state, atomic=False)
print("Step 2, index without blocking writes:")
print(" ", sql[0])

remove = [migrations.SeparateDatabaseAndState(
    state_operations=[migrations.RemoveField("attendance", "source")],
    database_operations=[],
)]
sql, state = sql_for(remove, state)
print("Step 3, remove from Django state only, SQL statements:", len(sql))

Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. It prints the SQL Django generates for each step, the same way sqlmigrate does, without applying it. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): Step 1, add column with a database default: ALTER TABLE "school_attendance" ADD COLUMN "source" varchar(10) DEFAULT 'manual' NOT NULL; Step 2, index without blocking writes: CREATE INDEX CONCURRENTLY "att_source_idx" ON "school_attendance" ("source"); Step 3, remove from Django state only, SQL statements: 0

Key points

  • Old and new code must both work with the schema during deploys
  • Add nullable or db_default columns, backfill, then constrain
  • AddIndexConcurrently with atomic = False on PostgreSQL
  • Remove fields in two releases with SeparateDatabaseAndState
  • Read sqlmigrate output and set lock_timeout

Common mistakes

  • Adding a NOT NULL column without a database default to a huge table in one step
  • Renaming a column while old code still reads the old name
  • Creating indexes without CONCURRENTLY on a busy PostgreSQL table
  • Running migrate from every container at startup

Follow-ups

  • How would you rename a heavily used column with no downtime?
  • Why must a migration using AddIndexConcurrently set atomic = False?
  • What is the difference between default= and db_default= during a migration?

Tips

  • Start from the rolling-deploy constraint: two code versions, one schema
  • Give the add, backfill, constrain sequence
  • Mention lock_timeout and reading sqlmigrate output
40.django-0040Hardsenior

How do you harden a Django site for production? Which settings does manage.py check --deploy look at?

Run python manage.py check --deploy and fix every warning: DEBUG off, a strong SECRET_KEY, ALLOWED_HOSTS set, HTTPS redirect, HSTS, secure and HttpOnly cookies, X-Frame-Options, and the SecurityMiddleware headers. Beyond settings, keep Django and dependencies patched, protect the admin, limit upload sizes, use parameterised queries, set a Content Security Policy (built in from Django 6.0), and log security events.

Full answer

Django ships safe defaults for many attacks (auto-escaping, CSRF, parameterised queries, clickjacking protection), but several production settings are off by default because they depend on HTTPS.

check --deploy warns about, among others:

  • DEBUG = True (W018) and a weak or short SECRET_KEY (W009).
  • Empty ALLOWED_HOSTS (W020).
  • SECURE_SSL_REDIRECT (W008): redirect HTTP to HTTPS. Often handled at the load balancer instead.
  • SECURE_HSTS_SECONDS (W004): sends Strict-Transport-Security, so browsers refuse plain HTTP for that period. Start small (3600), then raise to a year. Add SECURE_HSTS_INCLUDE_SUBDOMAINS and SECURE_HSTS_PRELOAD only when every subdomain serves HTTPS, because it is hard to undo.
  • SESSION_COOKIE_SECURE (W012) and CSRF_COOKIE_SECURE (W016): cookies sent only over HTTPS.
  • SecurityMiddleware missing (W001), and X_FRAME_OPTIONS (W019, defaults to DENY).

Some checks only run when the related middleware or app is present. The HSTS and SSL redirect warnings appear only once SecurityMiddleware is installed, and the session cookie warning only when django.contrib.sessions is installed, so a clean report on a half-configured project can mislead.

Other settings worth setting explicitly: SESSION_COOKIE_HTTPONLY (default True), SECURE_REFERRER_POLICY (default "same-origin"), SECURE_CROSS_ORIGIN_OPENER_POLICY, CSRF_TRUSTED_ORIGINS for cross-origin forms, DATA_UPLOAD_MAX_MEMORY_SIZE and FILE_UPLOAD_MAX_MEMORY_SIZE.

Content Security Policy: Django 6.0 added built-in CSP support (ContentSecurityPolicyMiddleware and SECURE_CSP). On 5.2 use the django-csp package.

Beyond settings:

  • Keep Django on a supported release and apply security releases quickly.
  • Protect /admin/ with strong passwords, 2FA (django-otp), and rate limiting on login (django-axes or proxy rules).
  • Use stronger password hashers (Argon2) and AUTH_PASSWORD_VALIDATORS.
  • Never build SQL with string formatting; never mark user input safe.
  • Scope every queryset by the current user to avoid IDOR.
  • Scan dependencies (pip-audit) in CI and run check --deploy --fail-level WARNING there too.
python
import django
from django.conf import settings

settings.configure(
    DEBUG=False,
    SECRET_KEY="short",
    ALLOWED_HOSTS=[],
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth"],
    MIDDLEWARE=[],
)
django.setup()

from django.core import checks


def deploy_warnings():
    return sorted(m.id for m in checks.run_checks(include_deployment_checks=True)
                  if m.id.startswith("security."))


print("no middleware:", deploy_warnings())

settings.MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]
print("middleware added:", deploy_warnings())

settings.SECRET_KEY = "k$8f2#mZq9!vR4tL0wXy7^bN3cJ6hD1sPe5gU-aT_iO2rWnE+Hs4Lq"  # load from env in real projects
settings.ALLOWED_HOSTS = ["portal.example.edu"]
settings.SECURE_SSL_REDIRECT = True
settings.SECURE_HSTS_SECONDS = 31536000
settings.SECURE_HSTS_INCLUDE_SUBDOMAINS = True
settings.SECURE_HSTS_PRELOAD = True
settings.SESSION_COOKIE_SECURE = True
settings.CSRF_COOKIE_SECURE = True

print("hardened:", deploy_warnings())

Standalone script. It runs Django's deployment checks before and after applying production settings. The SECRET_KEY shown is a demo value; real keys come from the environment. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): no middleware: ['security.W001', 'security.W002', 'security.W003', 'security.W009', 'security.W020'] middleware added: ['security.W004', 'security.W008', 'security.W009', 'security.W016', 'security.W020'] hardened: []

Key points

  • check --deploy lists missing production settings
  • HTTPS redirect, HSTS and secure cookies need HTTPS everywhere
  • Roll out HSTS gradually; preload is hard to undo
  • Django 6.0 has built-in CSP; use django-csp on 5.2
  • Patch quickly, protect the admin, scan dependencies

Common mistakes

  • Turning on HSTS preload before every subdomain supports HTTPS
  • Setting SECURE_SSL_REDIRECT behind a proxy without SECURE_PROXY_SSL_HEADER, causing redirect loops
  • Treating check --deploy as the whole security review
  • Leaving the admin on a public URL with no rate limiting or 2FA

Follow-ups

  • What does HSTS protect against that a redirect alone does not?
  • How would you add a Content Security Policy to a Django 5.2 site?
  • How do you protect the Django admin on a public site?

Tips

  • Name the settings and what attack each blocks
  • Mention the gradual HSTS rollout
  • Go beyond settings: patching, admin protection, dependency scanning