← Interview prep

Django interview questions

Models, ORM, auth, and Django web patterns.

100 questions · Page 3 of 5

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

Page 3 of 5

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

41.django-0041Hardsenior

How does Django protect against SQL injection and XSS, and how can developers accidentally break that protection?

The ORM and cursor.execute(sql, params) send values separately from SQL, so input is never parsed as SQL. Templates auto-escape output, which stops most XSS. Protection breaks when developers build SQL with f-strings or % formatting, pass user input to extra() or RawSQL without params, use |safe or mark_safe on user data, or put untrusted data into JavaScript or URLs without the right escaping. Use params, format_html() and json_script.

Full answer

SQL injection happens when user input becomes part of the SQL text. If a search box value x' OR '1'='1 is pasted into WHERE name = '...', the attacker changes the query.

Django's protection: QuerySets compile to SQL with placeholders, and the driver sends values separately. The same applies to raw SQL when you pass parameters:

python
cursor.execute("SELECT ... WHERE name = %s", [name])        # safe
Student.objects.raw("SELECT * FROM s WHERE name = %s", [name])  # safe
cursor.execute(f"SELECT ... WHERE name = '{name}'")         # vulnerable

Easy ways to break it:

  • f-strings, % or .format() in SQL strings, including inside raw(), RawSQL() and extra().
  • Quoting the placeholder yourself: '%s' (wrong; the driver adds quotes).
  • Identifiers such as column names or ORDER BY fields cannot be parameterised. Map user input to an allow-list: order = {"name": "name", "marks": "-marks"}.get(param, "name").

XSS (cross-site scripting) happens when user input becomes part of the page's HTML or JavaScript and runs in other users' browsers.

Django's protection: templates escape < > & ' " by default.

Ways to break it:

  • {{ comment|safe }}, {% autoescape off %} or mark_safe(user_text).
  • Building HTML in Python with f-strings. Use format_html("<b>{}</b>", name), which escapes arguments.
  • Putting data inside <script>. HTML escaping is not JavaScript escaping. Use {{ data|json_script:"data-id" }} and read it with JSON.parse.
  • href="{{ url }}" with a javascript: URL. Validate URL schemes.
  • Rich text from users needs an HTML sanitiser (for example nh3), not |safe.

Add a Content Security Policy as defence in depth, and keep session cookies HttpOnly so a script cannot read 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 connection, models
from django.template import Context, Engine
from django.utils.html import format_html


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


with connection.schema_editor() as editor:
    editor.create_model(Student)
Student.objects.create(name="Alok", fee_due=0)
Student.objects.create(name="Bina", fee_due=4500)

attack = "nobody' OR '1'='1"
table = Student._meta.db_table

with connection.cursor() as cur:
    cur.execute(f"SELECT name FROM {table} WHERE name = '{attack}'")          # vulnerable
    print("f-string SQL returned:", cur.fetchall())
    cur.execute(f"SELECT name FROM {table} WHERE name = %s", [attack])        # parameterised
    print("parameterised SQL returned:", cur.fetchall())
print("ORM returned:", list(Student.objects.filter(name=attack)))

ALLOWED_ORDER = {"name": "name", "fee": "-fee_due"}
user_sort = "fee_due; DROP TABLE x"
print("ordering used:", ALLOWED_ORDER.get(user_sort, "name"))

comment = '<img src=x onerror="alert(1)">'
engine = Engine()
print(engine.from_string("{{ c }}").render(Context({"c": comment})))
print(engine.from_string("{{ c|safe }}").render(Context({"c": comment})), "<- unsafe")
print(format_html("<b>{}</b>", comment))
print(engine.from_string('{{ data|json_script:"marks" }}').render(Context({"data": {"note": "</script><b>"}})))

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 vulnerable query is shown on purpose to demonstrate the attack against a throwaway in-memory database. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): f-string SQL returned: [('Alok',), ('Bina',)] parameterised SQL returned: [] ORM returned: [] ordering used: name &lt;img src=x onerror=&quot;alert(1)&quot;&gt; <img src=x onerror="alert(1)"> <- unsafe <b>&lt;img src=x onerror=&quot;alert(1)&quot;&gt;</b> <script id="marks" type="application/json">{"note": "\u003C/script\u003E\u003Cb\u003E"}</script>

Key points

  • ORM and parameterised cursor.execute keep values out of SQL text
  • f-strings in raw SQL are the classic injection bug
  • Use allow-lists for column names and ORDER BY
  • Templates auto-escape; |safe and mark_safe on user data cause XSS
  • Use format_html and json_script; sanitise rich text

Common mistakes

  • Formatting user input into raw SQL strings
  • Wrapping the %s placeholder in quotes
  • Passing user-chosen column names straight into order_by() or raw SQL
  • Using |safe or mark_safe on content that came from users
  • HTML-escaping data and then dropping it inside a script block

Follow-ups

  • How would you safely allow users to post formatted comments?
  • Why can a column name not be passed as a query parameter?
  • What does a Content Security Policy add on top of escaping?

Tips

  • Show the vulnerable and safe versions side by side
  • Name the ways developers bypass protection, not only the defaults
  • Mention json_script for data inside JavaScript
42.django-0042Hardsenior

How do you keep a Django REST Framework API fast and safe under load? Discuss pagination, throttling and serializer performance.

Always paginate list endpoints: PageNumberPagination or LimitOffsetPagination for small tables, CursorPagination for large or fast-changing ones because it avoids OFFSET and gives stable pages. Throttle with AnonRateThrottle, UserRateThrottle or ScopedRateThrottle backed by a shared cache such as Redis. Keep serializers cheap: prefetch related data, avoid per-row SerializerMethodField queries, and use plain values or read-only serializers for hot paths.

Full answer

Pagination

An unpaginated list endpoint works with 50 rows and fails with 500,000. Set a default in REST_FRAMEWORK:

  • PageNumberPagination: ?page=3. Simple; each page runs COUNT(*) plus OFFSET, both slow on huge tables.
  • LimitOffsetPagination: ?limit=20&offset=40. Same OFFSET cost.
  • CursorPagination: an opaque cursor encodes the position (for example the last created value). No count, no OFFSET, stable even when new rows arrive, but needs a unique, indexed ordering and does not allow jumping to page 37.

Set max_page_size so clients cannot ask for a million rows.

Throttling

  • AnonRateThrottle (by IP), UserRateThrottle (by user), ScopedRateThrottle (per endpoint, throttle_scope = "uploads").
  • Rates like "100/hour" in DEFAULT_THROTTLE_RATES. Exceeding them returns 429 with a Retry-After header.
  • Throttle state lives in the Django cache. With several servers, use Redis, otherwise each process counts separately.
  • DRF throttling is a fairness tool, not DDoS protection. Put coarse rate limits at the proxy or CDN too.
  • Behind a proxy, set NUM_PROXIES so DRF picks the real client IP from X-Forwarded-For.

Serializer performance

  • Nested serializers and SerializerMethodField often hide one query per row. Use select_related/prefetch_related in get_queryset() and test with assertNumQueries.
  • Annotate counts in SQL (Count("loans")) instead of obj.loans.count() per row.
  • For read-heavy endpoints, values() plus a plain serializer, or caching, can cut serialisation time a lot.
  • Return only fields the client needs; consider separate list and detail serializers.
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.core.cache import cache
from django.db import connection, models
from django.db.models import Count
from django.test.utils import CaptureQueriesContext
from django.urls import path
from rest_framework import generics, serializers
from rest_framework.pagination import CursorPagination
from rest_framework.test import APIClient
from rest_framework.throttling import AnonRateThrottle

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


class Member(models.Model):
    name = models.CharField(max_length=40)
    joined = models.IntegerField(unique=True)
    class Meta:
        app_label = "school"


class Loan(models.Model):
    member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name="loans")
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Member)
    editor.create_model(Loan)
for i in range(1, 8):
    m = Member.objects.create(name=f"member{i}", joined=i)
    Loan.objects.bulk_create([Loan(member=m) for _ in range(i % 3)])


class MemberSerializer(serializers.ModelSerializer):
    loan_count = serializers.IntegerField(read_only=True)
    class Meta:
        model = Member
        fields = ["name", "loan_count"]


class ByJoined(CursorPagination):
    ordering = "joined"
    page_size = 3


class FivePerMinute(AnonRateThrottle):
    rate = "5/min"


class MemberList(generics.ListAPIView):
    serializer_class = MemberSerializer
    pagination_class = ByJoined
    throttle_classes = [FivePerMinute]
    authentication_classes = []
    permission_classes = []

    def get_queryset(self):
        return Member.objects.annotate(loan_count=Count("loans"))


urlpatterns = [path("members/", MemberList.as_view())]
settings.ROOT_URLCONF = __name__

c = APIClient()
with CaptureQueriesContext(connection) as ctx:
    page1 = c.get("/members/").json()
print([m["name"] for m in page1["results"]], [m["loan_count"] for m in page1["results"]])
print("queries for one page:", len(ctx.captured_queries))
page2 = c.get(page1["next"]).json()
print([m["name"] for m in page2["results"]])

codes = [c.get("/members/").status_code for _ in range(4)]
r = c.get("/members/")
print(codes, r.status_code, "Retry-After:", r.headers.get("Retry-After") is not None)

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 djangorestframework. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['member1', 'member2', 'member3'] [1, 2, 0] queries for one page: 1 ['member4', 'member5', 'member6'] [200, 200, 200, 429] 429 Retry-After: True

Key points

  • Paginate every list endpoint and cap page size
  • CursorPagination avoids COUNT and OFFSET on large tables
  • Throttles need a shared cache across servers
  • Throttling is fairness, not DDoS protection
  • Prefetch and annotate to avoid per-row queries in serializers

Common mistakes

  • Shipping list endpoints without pagination
  • Using page number pagination with COUNT(*) on a table with tens of millions of rows
  • Relying on local-memory throttle state with several servers
  • Calling .count() or a related lookup per row inside a serializer

Follow-ups

  • How does CursorPagination encode its position?
  • How would you rate limit a login endpoint more strictly than the rest?
  • How do you find which serializer field causes extra queries?

Tips

  • Compare the three paginators with their costs
  • Mention 429 and Retry-After
  • Show the annotate-instead-of-per-row-count fix
43.django-0043Hardsenior

How does Django manage database connections, and when do you use CONN_MAX_AGE, CONN_HEALTH_CHECKS or connection pooling?

Django opens a database connection per thread on first use and, with the default CONN_MAX_AGE = 0, closes it at the end of every request. A positive CONN_MAX_AGE keeps persistent connections for that many seconds, and CONN_HEALTH_CHECKS = True tests them before reuse. Django 5.1 added native connection pooling for PostgreSQL through OPTIONS {"pool": True} with psycopg 3. External poolers such as PgBouncer are still common when many processes share one database.

Full answer

Opening a PostgreSQL connection costs a TCP handshake, TLS, authentication and a new server process, often a few milliseconds. Doing it on every request adds latency and load.

Django's built-in behaviour:

  • Connections are per thread (and per database alias). The first query in a thread opens one.
  • request_started and request_finished signals call close_old_connections(). With CONN_MAX_AGE = 0 (default) the connection closes after each request.
  • CONN_MAX_AGE = 60 keeps the connection open for reuse for up to 60 seconds; None means forever. Errors also cause a close.
  • CONN_HEALTH_CHECKS = True (Django 4.1+) checks a persistent connection before reusing it in a new request, so a database restart does not cause a failed request.

Native pooling (Django 5.1+, PostgreSQL with psycopg 3):

python
DATABASES = {"default": {
    "ENGINE": "django.db.backends.postgresql",
    "OPTIONS": {"pool": {"min_size": 2, "max_size": 10, "timeout": 10}},
}}

This uses psycopg_pool inside each process. Do not combine it with a non-zero CONN_MAX_AGE.

Sizing: every process has its own pool or persistent connections. 8 servers x 5 Gunicorn workers x 4 threads = 160 possible connections. PostgreSQL's default max_connections is 100, and each connection uses server memory. That is why teams put PgBouncer (in transaction pooling mode) between apps and the database: thousands of client connections share a small number of server connections. In transaction mode, avoid session-level features (server-side cursors, SET statements, advisory session locks); Django's DISABLE_SERVER_SIDE_CURSORS = True exists for this.

Async and threads: each thread gets its own connection, so thread pools inside views multiply connections. Close connections in long-running background threads with connections.close_all().

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.core.signals import request_finished, request_started
from django.db import connection, connections


def backend_pid():
    with connection.cursor() as cur:
        cur.execute("SELECT pg_backend_pid()")
        return cur.fetchone()[0]


def fake_request():
    request_started.send(sender=None)
    pid = backend_pid()
    request_finished.send(sender=None)
    return pid


connections["default"].settings_dict["CONN_MAX_AGE"] = 0
connection.close()
a, b = fake_request(), fake_request()
print("CONN_MAX_AGE=0, new connection each request:", a != b)

connections["default"].settings_dict["CONN_MAX_AGE"] = 60
connections["default"].settings_dict["CONN_HEALTH_CHECKS"] = True
connection.close()
a, b = fake_request(), fake_request()
print("CONN_MAX_AGE=60, same connection reused:", a == b)
connection.close()

# Native pool (Django 5.1+, psycopg 3 with the pool extra)
from django.db.backends.postgresql.base import DatabaseWrapper

pooled = DatabaseWrapper({**connections["default"].settings_dict, "CONN_MAX_AGE": 0,
                          "OPTIONS": {"pool": {"min_size": 1, "max_size": 4}}}, alias="pooled")
print("pool configured:", pooled.pool is not None, "max_size:", pooled.pool.max_size)
pooled.close_pool()

Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. The pool check needs `pip install "psycopg[binary,pool]"`. Ran on PostgreSQL 17; request start and finish are simulated by sending Django's request signals. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): CONN_MAX_AGE=0, new connection each request: True CONN_MAX_AGE=60, same connection reused: True pool configured: True max_size: 4

Key points

  • Connections are per thread and per alias
  • CONN_MAX_AGE = 0 closes after each request; > 0 reuses
  • CONN_HEALTH_CHECKS validates reused connections
  • Django 5.1 adds native PostgreSQL pooling with psycopg 3
  • Count connections across all processes; use PgBouncer at scale

Common mistakes

  • Raising CONN_MAX_AGE without counting total connections across all workers
  • Combining Django's native pool with persistent connections
  • Using PgBouncer transaction mode with server-side cursors still enabled
  • Leaving connections open in background threads

Follow-ups

  • How would you size a connection pool for 20 app servers?
  • What changes when you put PgBouncer in transaction mode?
  • Why might persistent connections cause errors after a database failover?

Tips

  • Explain the per-thread model first
  • Do the connection arithmetic out loud
  • Mention the Django 5.1 native pool and PgBouncer as options
44.django-0044Hardsenior

How do you design a reliable test suite for a large Django project? Cover TestCase vs TransactionTestCase, on_commit, override_settings, mocking and factories.

Use TestCase for most tests because each test is rolled back cheaply, and TransactionTestCase only when you need real commits, such as testing database locking or behaviour across connections. Test on_commit callbacks with captureOnCommitCallbacks, change settings with override_settings, mock outside services at the boundary, build data with factories, and guard performance with assertNumQueries. Run tests in parallel on the same database engine as production.

Full answer

A good Django suite is fast, isolated and trusted. Some choices that matter:

Test classes

  • SimpleTestCase: no database. Fast for pure functions, forms without models, template filters.
  • TestCase: wraps each test in a transaction (and the class in another) and rolls back. Fast. Data from setUpTestData is shared and restored per test.
  • TransactionTestCase: truncates tables after each test instead of rolling back. Slower, but needed when code depends on actual commits, multiple connections or threads, or select_for_update behaviour.
  • LiveServerTestCase: starts a real server for browser tests (Playwright, Selenium).

on_commit callbacks never run in TestCase because the transaction never commits. Use:

python
with self.captureOnCommitCallbacks(execute=True) as callbacks:
    enrol_student(...)

Settings and time

  • @override_settings(FEATURE_X=True) or with self.settings(...).
  • Freeze time with time-machine or freezegun for fee due dates and expiry logic.

Outside services

  • Mock at the boundary you own (payments.client.charge), not deep inside libraries. unittest.mock.patch or responses/respx for HTTP.
  • Emails go to django.core.mail.outbox automatically in tests.

Data

  • Factories (factory_boy) build valid objects with sensible defaults, so each test states only what matters. Fixtures in JSON tend to rot as models change.

Speed and trust

  • python manage.py test --parallel or pytest -n auto (pytest-xdist).
  • Run on the same database engine as production; SQLite hides PostgreSQL behaviour (constraints, locking, JSON operators).
  • Use fast password hashers in test settings.
  • Keep a few query-count tests on hot endpoints with assertNumQueries.
  • Test behaviour through public interfaces (views, services), not private helpers.
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 unittest
from unittest import mock

from django.core import mail
from django.db import connection, models, transaction
from django.test import TestCase, override_settings
from django.test.utils import setup_test_environment

settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"


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


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


class sms:
    @staticmethod
    def send(number, text):
        raise RuntimeError("real SMS gateway must not be called in tests")


def enrol(name, email):
    student = Student.objects.create(name=name, email=email)
    transaction.on_commit(lambda: mail.send_mail("Welcome", f"Hi {name}", "office@example.edu", [email]))
    if settings.SMS_ENABLED:
        sms.send("98xxxxxx00", f"{name} enrolled")
    return student


def make_student(**overrides):
    data = {"name": "Test Student", "email": "test@example.edu"}
    data.update(overrides)
    return Student(**data)


class EnrolTests(TestCase):
    @override_settings(SMS_ENABLED=False)
    def test_email_sent_after_commit(self):
        with self.captureOnCommitCallbacks(execute=True) as callbacks:
            enrol("Gita", "gita@example.edu")
        self.assertEqual(len(callbacks), 1)
        self.assertEqual(mail.outbox[0].to, ["gita@example.edu"])

    @override_settings(SMS_ENABLED=False)
    def test_no_email_without_commit(self):
        enrol("Hari", "hari@example.edu")
        self.assertEqual(len(mail.outbox), 0)

    @override_settings(SMS_ENABLED=True)
    def test_sms_is_mocked(self):
        with mock.patch.object(sms, "send") as fake_send:
            enrol("Ira", "ira@example.edu")
        fake_send.assert_called_once_with("98xxxxxx00", "Ira enrolled")

    def test_factory_defaults(self):
        self.assertEqual(make_student(name="Jay").email, "test@example.edu")


setup_test_environment()
suite = unittest.defaultTestLoader.loadTestsFromTestCase(EnrolTests)
result = unittest.TextTestRunner(verbosity=0, stream=open("/dev/null", "w")).run(suite)
print("ran:", result.testsRun, "failures:", len(result.failures), "errors:", len(result.errors))
for test, err in result.failures + result.errors:
    print(test, err)

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. make_student stands in for a factory_boy factory to keep the example dependency-free. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ran: 4 failures: 0 errors: 0

Key points

  • TestCase for most tests; TransactionTestCase for real commits
  • captureOnCommitCallbacks runs on_commit callbacks in TestCase
  • override_settings and time freezing for config and dates
  • Mock at your own boundary; factories for data
  • Test on the production database engine and in parallel

Common mistakes

  • Using TransactionTestCase everywhere and making the suite slow
  • Expecting on_commit callbacks to run inside TestCase
  • Mocking deep library internals instead of your own boundary
  • Testing on SQLite while production runs PostgreSQL

Follow-ups

  • How do you test code that uses select_for_update?
  • How would you make a 20-minute test suite run in 5 minutes?
  • What is the difference between a mock and a fake?

Tips

  • Explain why TestCase is fast and when it is not enough
  • Mention captureOnCommitCallbacks by name
  • Talk about suite speed and trust, not only individual tests
45.django-0045Hardsenior

How do bulk_create, bulk_update and upserts work in Django, and what do they skip compared with save()?

bulk_create() inserts many objects in few queries, bulk_update() updates chosen fields for many objects, and bulk_create(update_conflicts=True, unique_fields=..., update_fields=...) performs an upsert (INSERT ... ON CONFLICT DO UPDATE) on PostgreSQL, SQLite and MariaDB/MySQL. They are much faster than looping over save(), but they do not call save(), do not send pre_save/post_save signals and do not run model validation, so add those steps yourself if needed.

Full answer

Importing 50,000 exam results with save() in a loop sends 50,000 INSERT statements. The bulk methods batch them.

bulk_create(objs, batch_size=1000)

  • Inserts in batches. On PostgreSQL, SQLite 3.35+ and MariaDB 10.5+, primary keys are set on the objects afterwards.
  • ignore_conflicts=True skips rows that violate a unique constraint (primary keys are not set then).
  • update_conflicts=True, unique_fields=[...], update_fields=[...] (Django 4.1+) turns it into an upsert: insert new rows, update existing ones. Great for nightly syncs from another system.

bulk_update(objs, ["score"], batch_size=500)

  • Builds UPDATE ... SET score = CASE id WHEN 1 THEN ... END per batch. Large batches create very long SQL, so set batch_size.
  • Returns the number of rows matched (Django 4.0+).

QuerySet.update(...) is the fastest when all rows get the same change or an F() expression.

What bulk methods skip:

  • Model.save() overrides (so custom logic in save does not run).
  • pre_save / post_save signals.
  • full_clean() validation. Database constraints still apply.
  • auto_now fields are set by bulk_create but bulk_update only updates fields you list, so include updated_at explicitly and set it yourself.

Good import pattern:

  1. Read and validate input in Python (a form or serializer per row, or a vectorised check).
  2. Upsert in batches inside transaction.atomic() per batch.
  3. Report rows inserted, updated and rejected.
  4. Trigger side effects (cache clear, notifications) once after the batch, not per row.
python
import sys
import types

import django
from django.conf import settings

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

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

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


class Result(models.Model):
    roll_no = models.CharField(max_length=10)
    subject = models.CharField(max_length=20)
    score = models.IntegerField()

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


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

rows = [Result(roll_no=f"R{i:03d}", subject="Maths", score=50 + i % 50) for i in range(1000)]
with CaptureQueriesContext(connection) as ctx:
    Result.objects.bulk_create(rows, batch_size=250)
print("inserted:", Result.objects.count(), "queries:", len(ctx.captured_queries))

objs = list(Result.objects.filter(roll_no__in=["R001", "R002"]).order_by("roll_no"))
for o in objs:
    o.score += 5
print("bulk_update rows:", Result.objects.bulk_update(objs, ["score"]))

nightly_feed = [
    Result(roll_no="R001", subject="Maths", score=99),     # exists -> update
    Result(roll_no="R1000", subject="Maths", score=77),    # new -> insert
]
Result.objects.bulk_create(nightly_feed, update_conflicts=True,
                           unique_fields=["roll_no", "subject"], update_fields=["score"])
print(list(Result.objects.filter(roll_no__in=["R001", "R002", "R1000"])
           .order_by("roll_no").values_list("roll_no", "score")))
print("total:", Result.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): inserted: 1000 queries: 6 bulk_update rows: 2 [('R001', 99), ('R002', 57), ('R1000', 77)] total: 1001

Key points

  • bulk_create batches inserts; bulk_update batches field updates
  • update_conflicts=True gives an upsert
  • Bulk methods skip save(), signals and validation
  • Set batch_size for large data
  • List auto_now fields explicitly in bulk_update

Common mistakes

  • Expecting post_save signals or custom save() logic to run during bulk operations
  • Passing huge lists to bulk_update without batch_size
  • Forgetting updated_at in bulk_update's field list
  • Using ignore_conflicts and then relying on primary keys being set

Follow-ups

  • How would you import a 2 GB CSV file of attendance records?
  • What SQL does bulk_update generate and why can it be slow?
  • How do you report how many rows were inserted versus updated in an upsert?

Tips

  • Quote a rough speed difference: thousands of queries versus a handful
  • List exactly what bulk methods skip
  • Describe a full import pipeline, not only the method call
46.django-0046Hardsenior

How do you use multiple databases in Django, for example a read replica, and what does a database router do?

Define several aliases in DATABASES and either pick one explicitly with .using("alias") and save(using=...), or add a router class in DATABASE_ROUTERS whose db_for_read, db_for_write, allow_relation and allow_migrate methods choose automatically. A common setup sends writes to the primary and reads to replicas, while keeping reads that must see a just-written row on the primary to avoid replication lag surprises.

Full answer

Settings:

python
DATABASES = {
    "default": {...},          # primary, read-write
    "replica": {...},          # read-only copy
}
DATABASE_ROUTERS = ["core.routers.PrimaryReplicaRouter"]

Manual selection:

  • Student.objects.using("replica").filter(...)
  • obj.save(using="default")
  • transaction.atomic(using="default")

A router is a plain class with up to four methods. Each returns an alias, True/False, or None to let the next router decide:

  • db_for_read(model, **hints)
  • db_for_write(model, **hints)
  • allow_relation(obj1, obj2, **hints): may these two objects be related?
  • allow_migrate(db, app_label, model_name=None, **hints): should this model's tables exist on this database?

Uses:

  1. Read replicas to spread read load.
  2. Splitting apps across databases, such as analytics tables on a separate server.
  3. A legacy database that Django reads but never migrates (allow_migrate returns False, model has managed = False).

Replication lag is the main trap. Replicas run behind the primary by milliseconds to seconds. A user who updates their profile and is redirected to a page reading from a replica may see old data. Fixes: route reads to the primary for a short window after a write (stored in the session or a context variable), or read from the primary inside the same request after writing. Inside transaction.atomic(), keep all queries on the primary.

Limits: Django does not support foreign keys or joins across databases. Each database also needs its own transaction handling. In tests, set databases = {"default", "replica"} on the test class, and configure the replica with TEST: {"MIRROR": "default"} so it points at the same test database.

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() + "/primary.db"},
        "replica": {"ENGINE": "django.db.backends.sqlite3", "NAME": tempfile.mkdtemp() + "/replica.db"},
    },
    DATABASE_ROUTERS=["__main__.PrimaryReplicaRouter"],
)
django.setup()

import contextvars
from django.db import connections, models

stick_to_primary = contextvars.ContextVar("stick_to_primary", default=False)


class PrimaryReplicaRouter:
    def db_for_read(self, model, **hints):
        return "default" if stick_to_primary.get() else "replica"

    def db_for_write(self, model, **hints):
        stick_to_primary.set(True)      # read-your-writes for the rest of this request
        return "default"

    def allow_relation(self, obj1, obj2, **hints):
        return True

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return True


class Notice(models.Model):
    title = models.CharField(max_length=60)
    class Meta:
        app_label = "school"


for alias in ("default", "replica"):
    with connections[alias].schema_editor() as editor:
        editor.create_model(Notice)

# Pretend replication already copied one old row
Notice.objects.using("replica").create(title="Holiday on Monday")
Notice.objects.using("default").create(title="Holiday on Monday")

print("read goes to:", Notice.objects.all().db, list(Notice.objects.values_list("title", flat=True)))

Notice.objects.create(title="Exam timetable out")   # write -> primary, replica lags behind
print("after write, read goes to:", Notice.objects.all().db,
      list(Notice.objects.order_by("id").values_list("title", flat=True)))
print("replica still has:", list(Notice.objects.using("replica").values_list("title", flat=True)))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Two SQLite files stand in for a primary and a replica; the stale replica shows why read-your-writes routing matters. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): read goes to: replica ['Holiday on Monday'] after write, read goes to: default ['Holiday on Monday', 'Exam timetable out'] replica still has: ['Holiday on Monday']

Key points

  • Aliases in DATABASES; .using() and save(using=) for manual control
  • Routers implement db_for_read, db_for_write, allow_relation, allow_migrate
  • Returning None passes the decision to the next router
  • Replication lag: read-your-writes needs routing to primary
  • No cross-database joins or foreign keys

Common mistakes

  • Reading from a replica right after a write and showing stale data
  • Trying to join or add foreign keys across databases
  • Forgetting allow_migrate so tables are created on the wrong database
  • Running a transaction on one alias while queries go to another

Follow-ups

  • How would you implement read-your-writes across requests?
  • How do you test code that uses two databases?
  • When is sharding a better answer than replicas?

Tips

  • Show the router's four methods and what None means
  • Raise replication lag before the interviewer does
  • Mention test configuration with MIRROR
47.django-0047Hardsenior

How do you run background work in Django? Compare Celery, the Django 6.0 tasks framework and simple alternatives, and explain how to queue tasks safely.

Slow or unreliable work (emails, reports, API calls) should leave the request cycle and run in a worker process. Celery with Redis or RabbitMQ is the long-standing choice; Django 6.0 added a built-in tasks API (django.tasks) with pluggable backends; RQ and Dramatiq are lighter options. Queue tasks with transaction.on_commit so workers never see missing rows, pass IDs not objects, make tasks idempotent and set retries with backoff.

Full answer

A request should finish in well under a second. Generating a 40-page report card PDF, sending 2,000 fee reminder emails or calling a slow SMS gateway does not fit. Background processing moves that work to separate worker processes that read jobs from a queue.

Options:

  • Celery: mature, feature-rich (retries, schedules with beat, chains, rate limits), with Redis or RabbitMQ as broker. More moving parts to run and monitor.
  • Django 6.0 tasks framework (django.tasks): a standard @task decorator and .enqueue() API. Django ships development backends (immediate and dummy); production execution needs a backend package such as django-tasks with a database or Redis worker. It standardises the interface so you can swap backends.
  • RQ, Dramatiq, Huey: simpler queues for smaller teams.
  • Cron plus a management command: enough for nightly batch jobs.

Rules that prevent most bugs:

  1. Enqueue after commit. If you queue inside a transaction, the worker can start before the commit and fail to find the row, or run for a row that was rolled back. Use transaction.on_commit(lambda: send_receipt.delay(payment.id)). Celery 5.4+ has delay_on_commit() for the same effect.
  2. Pass IDs, not model instances. The worker loads fresh data.
  3. Make tasks idempotent. Brokers deliver at least once, so a task may run twice. Check "already sent" flags or use unique keys.
  4. Retry with backoff for temporary failures, with a maximum count, and send final failures to a dead-letter queue or alert.
  5. Set time limits so a stuck task does not block a worker forever.
  6. Keep tasks small and observable: log task IDs and track queue length.

Async views are not a replacement: an async def view still holds the HTTP request open until the work finishes.

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 queue
import threading

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


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


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

jobs = queue.Queue()   # stands in for Redis or RabbitMQ
log = []


def send_receipt(payment_id):
    """Idempotent task: loads fresh data by ID and skips work already done."""
    updated = Payment.objects.filter(pk=payment_id, receipt_sent=False).update(receipt_sent=True)
    log.append(f"payment {payment_id}: " + ("receipt sent" if updated else "already sent, skipped"))


def worker():
    while (job := jobs.get()) is not None:
        func, arg = job
        try:
            func(arg)
        except Payment.DoesNotExist:
            log.append("worker could not find the row")
    connections.close_all()


def record_payment(student, amount, fail=False):
    with transaction.atomic():
        p = Payment.objects.create(student=student, amount=amount)
        transaction.on_commit(lambda: jobs.put((send_receipt, p.id)))
        if fail:
            raise ValueError("bank declined")
    return p


t = threading.Thread(target=worker)
t.start()
p = record_payment("lakshmi", 1500)
try:
    record_payment("manoj", 900, fail=True)   # rolled back, so no job is queued
except ValueError:
    pass
jobs.put((send_receipt, p.id))                # duplicate delivery
jobs.put(None)
t.join()
print(log)
print(Payment.objects.count(), Payment.objects.get(pk=p.id).receipt_sent)

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. A thread and queue.Queue stand in for a real broker and worker so the example runs anywhere; with Celery the call would be transaction.on_commit(lambda: send_receipt.delay(p.id)). Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['payment 1: receipt sent', 'payment 1: already sent, skipped'] 1 True

Key points

  • Move slow or unreliable work to worker processes
  • Celery, django.tasks (6.0+), RQ/Dramatiq, or cron
  • Enqueue with transaction.on_commit
  • Pass IDs; make tasks idempotent; retry with backoff
  • Async views do not replace a task queue

Common mistakes

  • Queueing a task inside a transaction so the worker cannot find the new row
  • Passing a model instance to a task and acting on stale data
  • Assuming each task runs exactly once
  • Retrying forever with no backoff or alerting
  • Doing slow work in an async view instead of a worker

Follow-ups

  • How would you send 50,000 emails without overloading the mail provider?
  • What does at-least-once delivery mean for task design?
  • How would you monitor a task queue in production?

Tips

  • Name the on_commit rule early, it is the most common production bug
  • Explain idempotency with a concrete check
  • Know that Django 6.0 added a tasks API and what it does and does not include
48.django-0048Hardsenior

What are GeneratedField and db_default in Django 5.0, and when would you use them instead of Python-side defaults or computed properties?

db_default sets a default value in the database schema, so rows inserted by any client (raw SQL, other services) get it, and it can be an expression such as Now(). GeneratedField defines a column computed by the database from other columns, either stored or virtual, so it is always consistent and can be indexed and filtered. Use them when the value must be correct no matter which code writes the row.

Full answer

Both arrived in Django 5.0 and move logic from Python into the database.

db_default

  • created = models.DateTimeField(db_default=Now()) adds DEFAULT CURRENT_TIMESTAMP to the column.
  • Compare with default=, which Django fills in Python before INSERT. Rows inserted by raw SQL, a data pipeline or another service do not get Python defaults.
  • On insert, backends that support RETURNING (PostgreSQL, SQLite 3.35+, MariaDB 10.5+) send the database-chosen value back, so the instance has it right away. On MySQL, call refresh_from_db() to read it.
  • If both default and db_default are set, Python's default is used for ORM inserts, while the database default covers other writers.

GeneratedField

python
total = models.GeneratedField(
    expression=F("theory") + F("practical"),
    output_field=models.IntegerField(),
    db_persist=True,
)
  • The database computes the value. db_persist=True stores it (PostgreSQL only supports stored generated columns); False makes a virtual column computed on read where supported (SQLite, MySQL, Oracle).
  • You cannot assign it; it is read-only.
  • It can be indexed and used in filter() and order_by() like any column, unlike a Python @property.
  • On insert, the value comes back through RETURNING where supported. After an update in Django 5.2 the instance keeps the old value (the snippet shows this), so call refresh_from_db(). Django 6.0 refreshes generated fields after save() on PostgreSQL, SQLite and Oracle.
  • The expression must be deterministic and use only columns of the same row.

When to choose a @property instead: values that depend on other tables, change with time ("days until fee due"), or are only displayed, never filtered.

python
import sys
import types

import django
from django.conf import settings

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

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

from django.db import connection, models
from django.db.models import F, Value
from django.db.models.functions import Concat, Now


class ExamResult(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    theory = models.IntegerField()
    practical = models.IntegerField()
    status = models.CharField(max_length=10, db_default="pending")
    created = models.DateTimeField(db_default=Now())
    total = models.GeneratedField(expression=F("theory") + F("practical"),
                                  output_field=models.IntegerField(), db_persist=True)
    full_name = models.GeneratedField(expression=Concat("first_name", Value(" "), "last_name"),
                                      output_field=models.CharField(max_length=61), db_persist=False)

    class Meta:
        app_label = "school"


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

r = ExamResult.objects.create(first_name="Nikhil", last_name="Das", theory=58, practical=27)
print(r.full_name, r.total, r.status, r.created is not None)

# A writer outside the ORM still gets the database default and the computed columns
with connection.cursor() as cur:
    cur.execute(f"INSERT INTO {ExamResult._meta.db_table} (first_name, last_name, theory, practical) "
                "VALUES ('Pooja', 'Rao', 70, 25)")
print(list(ExamResult.objects.filter(total__gte=90).values_list("full_name", "total", "status")))

r.theory = 65
r.save()
print("after update, before refresh:", r.total)   # Django 5.2 keeps the old value
r.refresh_from_db()
print("after update:", r.total)

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): Nikhil Das 85 pending True [('Pooja Rao', 95, 'pending')] after update, before refresh: 85 after update: 92

Key points

  • db_default is a database-level default, also applied to non-Django writers
  • Python default= only applies to ORM inserts
  • GeneratedField is computed by the database from same-row columns
  • Generated columns are read-only and can be indexed and filtered
  • PostgreSQL supports only stored generated columns

Common mistakes

  • Assuming Python default= protects rows inserted by raw SQL or other services
  • Trying to assign a value to a GeneratedField
  • Reading a generated value after an update in Django 5.2 without refresh_from_db()
  • Using db_persist=False on PostgreSQL, which only supports stored generated columns

Follow-ups

  • What is the difference between a GeneratedField and an annotation?
  • How would you add a db_default column to a large table safely?
  • Which expressions are not allowed in a generated column?

Tips

  • Explain the difference from Python defaults with an outside writer
  • Mention indexing and filtering as the edge over @property
  • Note the version: both are Django 5.0+
49.django-0049Hardsenior

How do you write a custom authentication backend in Django, for example to log in with email, and how do object-level permissions fit in?

A backend is a class with authenticate(request, **credentials) returning a user or None, and get_user(user_id). Add it to AUTHENTICATION_BACKENDS; Django tries backends in order. Backends can also implement has_perm(user_obj, perm, obj=None) for object-level permissions, which Django's built-in ModelBackend does not provide for specific objects. Packages like django-guardian or django-rules are common for that.

Full answer

authenticate() loops over settings.AUTHENTICATION_BACKENDS. The first backend that returns a user wins. If a backend raises PermissionDenied, the loop stops and authentication fails.

An email backend:

python
class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(email__iexact=username)
        except User.DoesNotExist:
            User().set_password(password)   # spend similar time to resist timing attacks
            return None
        if user.check_password(password) and self.user_can_authenticate(user):
            return user

Details:

  • Subclassing ModelBackend keeps get_user(), group and model permission checks, and user_can_authenticate() (rejects inactive users).
  • Email must be unique for this to be safe. Enforce it with a database constraint, ideally case-insensitive (a UniqueConstraint on Lower("email")).
  • Running the password hasher even for unknown emails keeps response time similar, so attackers cannot discover registered emails by timing.
  • Django stores the backend path in the session at login, and get_user() of that backend loads the user on later requests.
  • Rate limit login attempts separately (proxy rules, django-axes).

Object-level permissions:

  • user.has_perm("school.change_note") checks model-level permission: may this user edit any note?
  • user.has_perm("school.change_note", note) passes an object. ModelBackend returns False for any object-level check. A custom backend can implement has_perm(user_obj, perm, obj=None) to say yes for the note's owner.
  • Django combines backends with OR: if any backend grants the permission, has_perm is True.
  • django-guardian stores per-object grants in tables; django-rules uses predicate functions without tables.

In DRF, object permissions are usually expressed in permission classes, but a backend keeps the rule in one place that the admin and templates can use too.

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 import authenticate, get_user_model
from django.contrib.auth.backends import BaseBackend, ModelBackend
from django.core.management import call_command
from django.db import connection, models

settings.PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]  # fast, demo only
settings.AUTHENTICATION_BACKENDS = ["__main__.EmailBackend", "__main__.OwnerBackend"]
call_command("migrate", verbosity=0)
User = get_user_model()


class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(email__iexact=username)
        except User.DoesNotExist:
            User().set_password(password)   # similar timing for unknown emails
            return None
        if user.check_password(password) and self.user_can_authenticate(user):
            return user
        return None


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


class OwnerBackend(BaseBackend):
    def has_perm(self, user_obj, perm, obj=None):
        return perm == "school.change_note" and isinstance(obj, Note) and obj.owner_id == user_obj.id


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

rina = User.objects.create_user("rina", email="Rina@Example.edu", password="Notebook-42")
sam = User.objects.create_user("sam", email="sam@example.edu", password="x")
User.objects.create_user("old", email="old@example.edu", password="x", is_active=False)

print(authenticate(username="rina@example.edu", password="Notebook-42"))
print(authenticate(username="rina@example.edu", password="wrong"))
print(authenticate(username="old@example.edu", password="x"))

note = Note.objects.create(owner=rina, text="Chemistry practical list")
print(rina.has_perm("school.change_note"), rina.has_perm("school.change_note", note),
      sam.has_perm("school.change_note", note))

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. MD5 hashing is used only to keep the demo fast. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): rina None None False True False

Key points

  • authenticate() returns a user or None; backends are tried in order
  • Subclass ModelBackend to keep get_user and permission checks
  • Enforce unique, case-insensitive emails
  • has_perm(user, perm, obj) enables object-level rules
  • Backends combine with OR for permissions

Common mistakes

  • Allowing duplicate emails and logging in the wrong account
  • Returning early for unknown emails and leaking which emails exist through timing
  • Forgetting to check is_active
  • Expecting ModelBackend to answer object-level permission checks

Follow-ups

  • How would you add login with a one-time code sent by SMS?
  • How do multiple backends combine for has_perm?
  • How would you share the same object rules between the admin and a DRF API?

Tips

  • Show both authenticate and has_perm on a backend
  • Mention the timing attack defence
  • Know that Django combines permission backends with OR
50.django-0050Hardsenior

A Django page that used to load in 200 ms now takes 4 seconds in production. How do you find and fix the cause?

Measure before changing anything. Use APM or tracing to see where time goes (database, external calls, Python, template rendering), compare with the last fast release, and reproduce with production-like data. Common causes are N+1 queries after a template or serializer change, a missing index after data growth, an unpaginated list, a slow external API, or cache misses. Fix the biggest cost, add a query-count or latency test, and watch the metric after deploying.

Full answer

A structured approach beats guessing.

  1. Confirm and scope the problem
  • Is it every request or some? One endpoint or all? Since when? Correlate with deploys, data growth, traffic peaks and infrastructure changes.
  • Look at percentiles (p50, p95, p99), not averages.
  1. Find where the time goes
  • An APM or tracing tool (OpenTelemetry with a backend, Sentry Performance, Datadog, New Relic) breaks a request into database spans, HTTP calls, cache calls and Python time.
  • Without APM: log query counts and time per request with a small middleware (as in the snippet), turn on PostgreSQL pg_stat_statements and log_min_duration_statement, and use Django Debug Toolbar or django-silk against a staging copy with realistic data.
  1. Typical causes and fixes
  • N+1 queries: a new field in a template or serializer touches a relation per row. Fix with select_related/prefetch_related, and add assertNumQueries to the test.
  • Missing index: data grew, the planner switched to a sequential scan. Check with EXPLAIN ANALYZE; add an index (concurrently).
  • Unbounded results: a list page without pagination now shows 40,000 rows.
  • External calls: an API that slowed down or timed out. Add timeouts, caching, or move to a background task.
  • Cache problems: a key changed or the cache server was replaced, so everything is computed again.
  • Locks: a migration or long transaction blocking writes. Check pg_stat_activity and pg_locks.
  • Python work: heavy loops or serialization. Profile with py-spy (safe on production processes) or cProfile locally.
  • Resource limits: too few workers, CPU throttling, connection pool exhaustion.
  1. Fix and protect
  • Change one thing at a time and measure again.
  • Add a regression guard: query-count test, load test in CI, or an alert on p95 latency.
  • Write a short incident note: cause, fix, and how it will be caught earlier next time.
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 logging
import time

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

logging.basicConfig(format="%(message)s", level=logging.INFO)
log = logging.getLogger("perf")


class QueryBudgetMiddleware:
    """Logs query count and database time per request; warns over budget."""

    def __init__(self, get_response, budget=10):
        self.get_response = get_response
        self.budget = budget

    def __call__(self, request):
        stats = {"count": 0, "time": 0.0}

        def wrapper(execute, sql, params, many, context):
            start = time.perf_counter()
            try:
                return execute(sql, params, many, context)
            finally:
                stats["count"] += 1
                stats["time"] += time.perf_counter() - start

        with connection.execute_wrapper(wrapper):
            response = self.get_response(request)
        level = logging.WARNING if stats["count"] > self.budget else logging.INFO
        log.log(level, "%s queries=%d over_budget=%s", request.path, stats["count"],
                stats["count"] > self.budget)
        response["X-Query-Count"] = str(stats["count"])
        return response


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


class Course(models.Model):
    title = models.CharField(max_length=40)
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Teacher)
    editor.create_model(Course)
t = Teacher.objects.create(name="Dr. Menon")
Course.objects.bulk_create([Course(title=f"Course {i}", teacher=t) for i in range(30)])


def slow_page(request):
    return HttpResponse(", ".join(f"{c.title} by {c.teacher.name}" for c in Course.objects.all()))


def fixed_page(request):
    qs = Course.objects.select_related("teacher")
    return HttpResponse(", ".join(f"{c.title} by {c.teacher.name}" for c in qs))


urlpatterns = [path("slow/", slow_page), path("fixed/", fixed_page)]
settings.ROOT_URLCONF = __name__
settings.MIDDLEWARE = [f"{__name__}.QueryBudgetMiddleware"]

c = Client()
print("slow:", c.get("/slow/")["X-Query-Count"])
print("fixed:", c.get("/fixed/")["X-Query-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. Log lines from the middleware go to stderr; stdout shows the query counts from the response header. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): slow: 31 fixed: 1

Key points

  • Measure with percentiles and tracing before changing code
  • Correlate with deploys and data growth
  • Check N+1, missing indexes, unbounded lists, external calls, cache, locks
  • Use EXPLAIN ANALYZE, pg_stat_statements, py-spy
  • Add regression guards such as assertNumQueries and latency alerts

Common mistakes

  • Optimising code before measuring where time goes
  • Looking only at averages and missing slow p99 requests
  • Testing on a tiny local database that hides missing indexes
  • Fixing the symptom without adding a regression test or alert

Follow-ups

  • How would you profile a production process without restarting it?
  • What does EXPLAIN ANALYZE show that EXPLAIN does not?
  • How would you prevent this regression from shipping again?

Tips

  • Describe a method, not a single trick
  • Name concrete tools at each step
  • Close with how you would prevent a repeat
51.django-0051Easyfresher

How do you create, read, update and delete rows with the Django ORM, and what do get_or_create() and update_or_create() return?

Create with Model.objects.create() or instance.save(), read with get() for exactly one row or filter() for many, update with save() on an instance or update() on a queryset, and delete with delete(). get_or_create() and update_or_create() return a tuple of (object, created) so the caller knows whether a row was inserted.

Full answer

CRUD maps to four groups of ORM calls.

Create: Student.objects.create(name="Asha") inserts immediately. Alternatively build Student(name="Asha") and call .save().

Read: get() returns one object and raises DoesNotExist if nothing matches or MultipleObjectsReturned if more than one does. filter() returns a lazy QuerySet that may hold zero, one or many rows. first() and last() return an object or None.

Update: change attributes and call save() (writes every column unless update_fields is given), or run Student.objects.filter(...).update(grade="A"), which issues one UPDATE statement, skips save() and signals, and returns the number of rows changed.

Delete: instance.delete() or queryset.delete(). Both return (total_deleted, {label: count}), including cascaded rows.

get_or_create(defaults=..., **lookup) looks up by the keyword arguments, and creates the row with the lookup values plus defaults if none exists. update_or_create() does the same but applies defaults as updates when the row exists. Both return (obj, created). They are safe against races only when the lookup fields are backed by a unique constraint; otherwise two requests can both insert, and a later get() raises MultipleObjectsReturned.

Do not call get() for something that might not exist without handling DoesNotExist, or use filter(...).first().

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 Student(models.Model):
    roll_no = models.CharField(max_length=10, unique=True)
    name = models.CharField(max_length=40)
    grade = models.CharField(max_length=2, default="C")

    class Meta:
        app_label = "school"


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

asha = Student.objects.create(roll_no="BCA-1", name="Asha")
Student(roll_no="BCA-2", name="Ravi").save()
print(Student.objects.get(roll_no="BCA-1").name)

try:
    Student.objects.get(roll_no="BCA-9")
except Student.DoesNotExist:
    print("no such student")

asha.grade = "A"
asha.save(update_fields=["grade"])
print(Student.objects.filter(grade="C").update(grade="B"), "row updated in one query")

obj, created = Student.objects.get_or_create(roll_no="BCA-3", defaults={"name": "Kiran"})
print(obj.name, created)
obj, created = Student.objects.get_or_create(roll_no="BCA-3", defaults={"name": "Other"})
print(obj.name, created)
obj, created = Student.objects.update_or_create(roll_no="BCA-3", defaults={"grade": "A"})
print(obj.grade, created)
print(Student.objects.filter(grade="A").delete())

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): Asha no such student 1 row updated in one query Kiran True Kiran False A False (2, {'school.Student': 2})

Key points

  • create() inserts; get() expects exactly one row
  • update() on a queryset is one SQL statement and skips save() and signals
  • delete() returns the number of rows removed, cascades included
  • get_or_create returns (obj, created); needs a unique constraint to be race-safe

Common mistakes

  • Calling get() when zero or several rows are possible without handling the exceptions
  • Using get_or_create on fields that are not unique
  • Expecting update() to call save() or send signals
  • Forgetting that queryset.delete() cascades to related rows

Follow-ups

  • How would you make get_or_create safe under concurrent requests?
  • What does save(update_fields=[...]) change in the SQL?
  • How does bulk_create differ from calling create() in a loop?

Tips

  • State which exceptions get() raises
  • Mention the (obj, created) tuple
  • Name the unique-constraint requirement
52.django-0052Easyfresher

What are field lookups in Django such as __contains, __gte, __in and __isnull, and how do filter(), exclude() and order_by() combine them?

A lookup is a double-underscore suffix on a field name that selects the comparison: exact, iexact, contains, icontains, startswith, gt, gte, lt, lte, in, range, isnull, and date parts like year. filter() keeps matching rows, exclude() removes them, keyword arguments in one call are combined with AND, and order_by() sorts, with a leading minus for descending order.

Full answer

Without a suffix, name="Asha" means name__exact="Asha". Common lookups:

  • Text: name__icontains="sha" (case-insensitive substring), name__startswith="A", name__iexact="asha".
  • Numbers and dates: score__gte=60, score__lt=40, score__range=(40, 60), joined__year=2026.
  • Sets: grade__in=["A", "B"].
  • Nulls: email__isnull=True. Writing email=None also works, but isnull is clearer.
  • Related fields use the same double underscore to cross relations: student__class_room__name="10A".

Several arguments in one filter() are joined by AND. Chaining .filter(a).filter(b) is the same for single-valued fields, but differs for multi-valued relations (each filter call can match a different related row). Use Q objects for OR and NOT (see the Q objects question).

exclude(grade="A") generates NOT (grade = 'A'). Nulls matter: SQL's NOT on a NULL value is unknown, and Django adds extra conditions to keep nullable columns correct, so check the SQL with str(qs.query) when unsure.

order_by("-score", "name") sorts by score descending, then name. order_by("?") is random and slow on large tables. Slicing qs[:10] adds LIMIT and OFFSET, and negative indexes are not allowed.

Lookups are case-sensitive or not depending on the database: contains on SQLite is case-insensitive for ASCII, but on PostgreSQL it is case-sensitive, which is why icontains is the portable choice.

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 Student(models.Model):
    name = models.CharField(max_length=40)
    score = models.IntegerField()
    grade = models.CharField(max_length=2)
    email = models.EmailField(null=True, blank=True)

    class Meta:
        app_label = "school"


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

rows = [("Asha", 91, "A", "asha@example.com"), ("Ravi", 58, "C", None), ("Kiran", 74, "B", None), ("Meera", 66, "B", "m@example.com")]
for n, s, g, e in rows:
    Student.objects.create(name=n, score=s, grade=g, email=e)

names = lambda qs: [s.name for s in qs]
print(names(Student.objects.filter(name__icontains="ra")))
print(names(Student.objects.filter(score__gte=60, grade="B")))
print(names(Student.objects.filter(grade__in=["A", "C"])))
print(names(Student.objects.filter(email__isnull=True)))
print(names(Student.objects.exclude(grade="B").order_by("-score")))
print(names(Student.objects.filter(score__range=(60, 80)).order_by("name")[:1]))
print(str(Student.objects.filter(score__gte=60).exclude(grade="C").query))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['Ravi', 'Kiran', 'Meera'] ['Kiran', 'Meera'] ['Asha', 'Ravi'] ['Ravi', 'Kiran'] ['Asha', 'Ravi'] ['Kiran'] SELECT "school_student"."id", "school_student"."name", "school_student"."score", "school_student"."grade", "school_student"."email" FROM "school_student" WHERE ("school_student"."score" >= 60 AND NOT ("school_student"."grade" = C))

Key points

  • Suffix after double underscore picks the comparison
  • Arguments in one filter() are ANDed
  • exclude() negates; mind nullable columns
  • order_by('-field') sorts descending
  • Use icontains for portable case-insensitive search

Common mistakes

  • Chaining filter() on multi-valued relations and expecting AND on the same related row
  • Using exact lookups for user search instead of icontains
  • Using order_by('?') on large tables
  • Forgetting that contains is case-sensitive on some databases

Follow-ups

  • How does filter().filter() differ from a single filter() across a ManyToMany?
  • How do you do OR queries?
  • How would you search across several fields?

Tips

  • Give 4 lookups from memory
  • Explain AND versus OR
  • Show you can print the SQL
53.django-0053Easyfresher

How does ManyToManyField work in Django, and when do you need a custom through model?

ManyToManyField creates a hidden join table and gives both sides add(), remove(), set(), clear() and queryset access. Use an explicit through model when the relationship itself has data, such as enrolment date or grade, or when you need extra constraints. With a custom through model, create the link by creating through-model rows (add() accepts through_defaults).

Full answer

A student can attend many courses and a course has many students. Django models this with one field on either side: courses = models.ManyToManyField(Course, related_name="students"). The migration creates a table with two foreign keys and a unique pair.

API on the manager: student.courses.add(c1, c2), remove(c1), set([c1, c3]) (replaces the whole set), clear(), and student.courses.filter(...). The reverse side is course.students.all().

Extra data needs a through model:

python
class Enrolment(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    joined = models.DateField()
    grade = models.CharField(max_length=2, blank=True)

courses = models.ManyToManyField(Course, through="Enrolment")

Since Django 2.2 you may call add(), set() and create() on a through relationship if you pass through_defaults={"joined": ...}. Before that, you had to create Enrolment rows directly, which still works and is often clearer.

Decide at the start: switching a plain M2M to a through model later is painful because the join table must be migrated by hand. Add a UniqueConstraint on the pair in the through model to prevent duplicates, and use prefetch_related("courses") to avoid N+1 queries when listing.

Self-referential M2M (friends) uses ManyToManyField("self", symmetrical=True).

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 Course(models.Model):
    title = models.CharField(max_length=40)

    class Meta:
        app_label = "school"


class Student(models.Model):
    name = models.CharField(max_length=40)
    courses = models.ManyToManyField(Course, through="Enrolment", related_name="students")

    class Meta:
        app_label = "school"


class Enrolment(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    grade = models.CharField(max_length=2, blank=True)

    class Meta:
        app_label = "school"
        constraints = [models.UniqueConstraint(fields=["student", "course"], name="one_enrolment_per_pair")]


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

asha, ravi = Student.objects.create(name="Asha"), Student.objects.create(name="Ravi")
db, net = Course.objects.create(title="DBMS"), Course.objects.create(title="Networks")

asha.courses.add(db, net, through_defaults={"grade": "A"})
ravi.courses.add(db)
print([c.title for c in asha.courses.all()])
print(sorted(s.name for s in db.students.all()))
print(Enrolment.objects.get(student=asha, course=db).grade)

asha.courses.set([net])
print([c.title for c in asha.courses.all()])
print(Student.objects.prefetch_related("courses").get(name="Ravi").courses.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): ['DBMS', 'Networks'] ['Asha', 'Ravi'] A ['Networks'] 1

Key points

  • M2M creates a join table; both sides get manager methods
  • set() replaces, add() appends, clear() empties
  • Use through= when the link carries data
  • Add a unique constraint on the pair; prefetch_related avoids N+1

Common mistakes

  • Choosing a plain M2M and later needing extra columns
  • Forgetting a unique constraint on the pair in a through model
  • Looping over students and querying courses each time instead of prefetch_related
  • Using add() on a through model without through_defaults for required fields

Follow-ups

  • How do you convert an existing M2M to a through model without losing data?
  • How do you query students who take both DBMS and Networks?
  • What happens to the join rows when a student is deleted?

Tips

  • Explain the hidden join table
  • Give an example of a through model
  • Mention N+1 and prefetch_related
54.django-0054Easyfresher

What is a OneToOneField in Django, and how do reverse relations and related_name work for ForeignKey and OneToOneField?

OneToOneField is a ForeignKey with a unique constraint: each row on one side links to at most one row on the other. Both relationship types create a reverse accessor on the target model: <model>_set for ForeignKey and <model> for OneToOneField, unless related_name overrides it. Reverse one-to-one access raises RelatedObjectDoesNotExist when no linked row exists.

Full answer

Use a OneToOneField for extension data such as a StudentProfile attached to a user, or to split a very wide table.

python
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")

Forward access: profile.user. Reverse access: user.profile, a single object, not a manager. If no profile exists, Django raises User.profile.RelatedObjectDoesNotExist (a subclass of AttributeError and DoesNotExist), so use hasattr(user, "profile") or catch it.

ForeignKey reverse access is a manager: class_room.student_set.all() by default. Setting related_name="students" renames it to class_room.students.all() and also the query name: ClassRoom.objects.filter(students__name="Asha") (use related_query_name to change only the query name).

Rules:

  • Two foreign keys from one model to the same target (for example created_by and reviewed_by) clash on the default reverse name, so give each a distinct related_name. The system check fails otherwise (fields.E304).
  • related_name="+" disables the reverse accessor.
  • For queries, select_related("profile") follows one-to-one in either direction in a single JOIN, which avoids an extra query per row.

Pick related_name as a plural noun for ForeignKey (students) and a singular noun for OneToOne (profile) so the code reads naturally.

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 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 Profile(models.Model):
    student = models.OneToOneField(Student, on_delete=models.CASCADE, related_name="profile")
    bio = models.CharField(max_length=80)

    class Meta:
        app_label = "school"


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

room = ClassRoom.objects.create(name="10A")
asha = Student.objects.create(name="Asha", class_room=room)
ravi = Student.objects.create(name="Ravi", class_room=room)
Profile.objects.create(student=asha, bio="Loves maths")

print([s.name for s in room.students.all()])                 # reverse ForeignKey: a manager
print(asha.profile.bio)                                      # reverse OneToOne: an object
try:
    ravi.profile
except Profile.DoesNotExist as exc:
    print("no profile:", type(exc).__name__)
print(ClassRoom.objects.filter(students__name="Ravi").count())
print(Student.objects.select_related("profile").get(name="Asha").profile.bio)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['Asha', 'Ravi'] Loves maths no profile: RelatedObjectDoesNotExist 1 Loves maths

Key points

  • OneToOne is a unique ForeignKey
  • Reverse of ForeignKey is a manager; reverse of OneToOne is an object
  • related_name renames the reverse accessor and the query name
  • Two FKs to the same model need distinct related_name values
  • select_related follows one-to-one in a single query

Common mistakes

  • Expecting a reverse OneToOne to return None instead of raising
  • Using the same default reverse name for two ForeignKeys to one model
  • Accessing reverse relations in a loop without select_related
  • Forgetting that related_name also changes the filter keyword

Follow-ups

  • How does Django name the reverse accessor if you omit related_name?
  • How would you attach optional profile data to the built-in User?
  • What does on_delete=PROTECT do on the OneToOne side?

Tips

  • Separate manager vs object in the reverse direction
  • Mention the error for missing reverse object
  • Show select_related
55.django-0055Easyfresher

What does the Meta class do in a Django model, and why define __str__()?

Meta holds model-level options that are not fields: default ordering, database table name, verbose names, constraints, indexes, unique_together-style rules and abstract inheritance settings. __str__() returns the human-readable label used by the admin, the shell, forms' select boxes and logs, so without it you see 'Student object (1)'.

Full answer
python
class Student(models.Model):
    name = models.CharField(max_length=40)
    joined = models.DateField()

    class Meta:
        ordering = ["name"]
        verbose_name_plural = "students"
        indexes = [models.Index(fields=["joined"])]
        constraints = [models.UniqueConstraint(fields=["name", "joined"], name="uniq_name_joined")]

    def __str__(self):
        return self.name

Common Meta options:

  • ordering: default ORDER BY for every query. It adds sorting cost to each query, so for big tables only set it when most reads need it. order_by() with no arguments clears it.
  • verbose_name and verbose_name_plural: names shown in the admin.
  • db_table: override the table name, which defaults to <app_label>_<model>.
  • indexes, constraints: database-level rules. Prefer constraints over the older unique_together.
  • abstract = True: the model is a template for children and gets no table.
  • app_label: needed for models defined outside an installed app.
  • get_latest_by: used by latest() and earliest().
  • permissions, default_related_name, managed = False (Django does not create or change the table, used for legacy tables or views).

__str__ is displayed in the admin list, in dropdowns for ForeignKey fields, and in print(obj). Keep it short, avoid queries inside it (it runs for every row of a list and creates N+1 problems when it touches a relation), and return a string.

Changing ordering or verbose_name produces an AlterModelOptions migration with no SQL, while changing db_table renames the table.

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 Student(models.Model):
    name = models.CharField(max_length=40)
    joined = models.DateField()

    class Meta:
        app_label = "school"
        ordering = ["name"]
        verbose_name_plural = "students"
        constraints = [models.UniqueConstraint(fields=["name", "joined"], name="uniq_name_joined")]

    def __str__(self):
        return self.name


class Plain(models.Model):
    class Meta:
        app_label = "school"


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

import datetime
for n in ("Ravi", "Asha", "Kiran"):
    Student.objects.create(name=n, joined=datetime.date(2026, 1, 5))

print(list(Student.objects.all()))                         # uses __str__ and Meta.ordering
print(str(Student.objects.all().query)[-40:])
print(str(Student.objects.order_by().query)[-30:])         # order_by() clears default ordering
print(str(Plain()))                                        # no __str__ defined
print(Student._meta.verbose_name_plural, Student._meta.db_table)

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): [<Student: Asha>, <Student: Kiran>, <Student: Ravi>] nt" ORDER BY "school_student"."name" ASC "joined" FROM "school_student" Plain object (None) students school_student

Key points

  • Meta carries ordering, indexes, constraints, table names and abstract settings
  • __str__ gives readable labels in admin, shell and forms
  • Default ordering adds ORDER BY to every query
  • Avoid relation lookups inside __str__ (N+1)
  • Prefer constraints over unique_together

Common mistakes

  • Skipping __str__ and getting 'Student object (1)' everywhere
  • Setting default ordering on a huge table that rarely needs it
  • Using unique_together in new code
  • Running queries inside __str__

Follow-ups

  • How do you make a field-level ordering that does not affect every query?
  • What does managed = False do?
  • How do abstract base classes use Meta?

Tips

  • List 5 Meta options
  • Warn about default ordering cost
  • Mention __str__ in admin
56.django-0056Easyfresher

What happens inside Django between receiving an HTTP request and sending the response?

The web server hands the request to Django through WSGI or ASGI. Django builds an HttpRequest, passes it down the MIDDLEWARE list, resolves the URL to a view with the URLconf, calls the view (which may use the ORM and templates), and returns an HttpResponse that travels back up through the middleware in reverse order before the server sends it.

Full answer

Steps for one request:

  1. The server (Gunicorn, Uvicorn, runserver) calls Django's WSGI or ASGI handler.
  2. The handler creates an HttpRequest with method, headers, GET, POST and body.
  3. Each middleware in MIDDLEWARE runs top to bottom (its code before get_response). Security, sessions, CSRF and authentication middleware attach data such as request.session and request.user.
  4. The URL resolver matches request.path_info against ROOT_URLCONF, and finds a view plus its arguments. No match raises Http404.
  5. process_view hooks of middleware run, then the view runs. The view reads data (ORM), makes decisions and returns an HttpResponse, JsonResponse, redirect or a TemplateResponse.
  6. Template rendering happens (lazily for TemplateResponse).
  7. The response goes back up through the middleware bottom to top (code after get_response), where headers, cookies and compression are added.
  8. The handler sends the response. Exceptions are converted into 404, 403, 500 responses by the handler or error views; process_exception hooks run first.

Order matters. SessionMiddleware must come before AuthenticationMiddleware, because the user is read from the session. A middleware that returns early (like a maintenance page) short-circuits everything below it.

Signals such as request_started and request_finished fire at the edges of this flow, and database connections are closed when the request ends.

python
import sys
import types

import django
from django.conf import settings

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

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

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

events = []


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

    def __call__(self, request):
        events.append("one: before view")
        response = self.get_response(request)
        events.append("one: after view")
        return response


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

    def __call__(self, request):
        events.append("two: before view")
        response = self.get_response(request)
        events.append("two: after view")
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        events.append(f"two: process_view -> {view_func.__name__}")


def hello(request):
    events.append("view runs")
    return HttpResponse("hello")


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

r = Client().get("/hello/")
print(r.status_code, r.content)
print("\n".join(events))
events.clear()
print(Client().get("/missing/").status_code, events)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The middleware classes live in the same file, referenced through the __main__ module path. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 b'hello' one: before view two: before view two: process_view -> hello view runs two: after view one: after view 404 ['one: before view', 'two: before view', 'two: after view', 'one: after view']

Key points

  • Server calls WSGI or ASGI handler, which builds HttpRequest
  • Middleware runs in order down, then in reverse on the way back
  • URLconf resolves the view; no match gives 404
  • The view returns a response object
  • Middleware order is a dependency order

Common mistakes

  • Putting AuthenticationMiddleware before SessionMiddleware
  • Assuming the view is the only code that touches the request
  • Putting heavy work in middleware that runs on every request
  • Forgetting that exceptions are turned into responses by the handler

Follow-ups

  • What is the difference between process_view and the __call__ style?
  • Where does CSRF checking happen?
  • What changes in the flow under ASGI?

Tips

  • Walk through the steps in order
  • Mention reverse order for responses
  • Name one order dependency
57.django-0057Easyfresher

How do you read query strings, form data, JSON bodies and headers from a Django HttpRequest, and how do you return JSON?

request.GET and request.POST are QueryDict objects (use get() and getlist()), request.body holds raw bytes that you decode with json.loads for JSON APIs, request.headers is a case-insensitive mapping, and request.method tells you the verb. JsonResponse serialises a dict to JSON with the right content type, and needs safe=False to return a list.

Full answer

Key attributes of HttpRequest:

  • request.method: "GET", "POST" and so on.
  • request.GET: query string. request.GET.get("page", "1") returns the last value; getlist("tag") returns all values.
  • request.POST: form-encoded body (only for form content types). It is empty for JSON requests.
  • request.body: raw bytes. For JSON, json.loads(request.body) and handle json.JSONDecodeError by returning 400.
  • request.headers["User-Agent"] is case-insensitive and normalises names (Content-Type). request.META holds the raw WSGI environ with keys such as HTTP_USER_AGENT and REMOTE_ADDR.
  • request.FILES for uploads, request.COOKIES, request.user and request.session when middleware is enabled, request.path, request.get_full_path() and request.build_absolute_uri().

Responses:

python
return JsonResponse({"ok": True}, status=201)
return JsonResponse([1, 2, 3], safe=False)   # lists need safe=False

JsonResponse uses DjangoJSONEncoder, which handles datetime, Decimal and UUID. Use HttpResponseBadRequest, Http404 or status= for errors.

Validate input: int(request.GET.get("page")) raises on bad input, which becomes a 500. Parse safely or use a Form. For real APIs, Django REST Framework gives parsing, validation and content negotiation, so use it once endpoints grow.

Restrict methods with @require_http_methods(["GET", "POST"]) or @require_POST.

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 json

from django.http import JsonResponse
from django.test import RequestFactory
from django.views.decorators.http import require_http_methods


@require_http_methods(["GET", "POST"])
def echo(request):
    if request.method == "GET":
        return JsonResponse({"page": request.GET.get("page", "1"), "tags": request.GET.getlist("tag"),
                             "agent": request.headers.get("user-agent")})
    if request.content_type == "application/json":
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({"error": "invalid JSON"}, status=400)
        return JsonResponse({"json": data}, status=201)
    return JsonResponse({"form": request.POST.dict()})


rf = RequestFactory()
print(json.loads(echo(rf.get("/echo/?page=2&tag=a&tag=b", HTTP_USER_AGENT="demo-client")).content))
print(json.loads(echo(rf.post("/echo/", {"name": "Asha"})).content))
r = echo(rf.post("/echo/", data=json.dumps({"score": 91}), content_type="application/json"))
print(r.status_code, json.loads(r.content))
print(echo(rf.post("/echo/", data="{bad", content_type="application/json")).status_code)
print(echo(rf.delete("/echo/")).status_code)
print(JsonResponse([1, 2], safe=False).content)

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): {'page': '2', 'tags': ['a', 'b'], 'agent': 'demo-client'} {'form': {'name': 'Asha'}} 201 {'json': {'score': 91}} 400 405 b'[1, 2]'

Key points

  • GET and POST are QueryDicts; use get() and getlist()
  • JSON bodies come from request.body, not request.POST
  • request.headers is case-insensitive; META has raw keys
  • JsonResponse needs safe=False for non-dict data
  • Return 400 on bad JSON instead of letting it crash

Common mistakes

  • Reading JSON from request.POST
  • Not catching JSONDecodeError
  • Returning a list from JsonResponse without safe=False
  • Trusting query-string values without validation

Follow-ups

  • How does request.GET differ from request.POST?
  • What would DRF add on top of this?
  • How do you read client IP safely behind a proxy?

Tips

  • Name request.body for JSON
  • Mention 400 for bad JSON
  • Explain QueryDict get vs getlist
58.django-0058Easyfresher

What are sessions in Django, how do they differ from cookies, and where is session data stored?

A cookie stores a small value in the browser. A session keeps data on the server and sends the browser only a random session ID in a cookie. Django's request.session behaves like a dict, defaults to the database backend, and can instead use cache, cached_db, files or signed cookies. Never store secrets in plain cookies, and treat session data as server-trusted but expiry and fixation as risks.

Full answer

HTTP is stateless, so sites need a way to remember a visitor.

Cookies: response.set_cookie("theme", "dark", max_age=86400, httponly=True, secure=True, samesite="Lax"). The browser sends them on every matching request, and the user can read and change them. Use get_signed_cookie / set_signed_cookie to detect tampering.

Sessions: the browser holds only sessionid (random, unguessable). The data lives on the server and is loaded via request.session["cart"]. SessionMiddleware provides it, and login uses it to remember request.user.

Backends (SESSION_ENGINE):

  • django.contrib.sessions.backends.db (default): table django_session, survives restarts, extra query per request that uses the session. Clear old rows with manage.py clearsessions.
  • cache: fast, but data is lost if the cache is flushed.
  • cached_db: write-through, a good default for busy sites.
  • signed_cookies: no server storage, but data lives in the cookie, is readable (signed, not encrypted), size-limited, and cannot be revoked.

Useful settings: SESSION_COOKIE_AGE, SESSION_COOKIE_SECURE, SESSION_COOKIE_HTTPONLY (default True), SESSION_COOKIE_SAMESITE, SESSION_EXPIRE_AT_BROWSER_CLOSE.

Security: login() rotates the session key to prevent fixation; keep sessions small and JSON-serialisable (the default serializer is JSON); changing a password invalidates the user's other sessions through the session auth hash; request.session.flush() on logout.

python
import sys
import types

import django
from django.conf import settings

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

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

from django.contrib.sessions.models import Session
from django.db import connection
from django.http import JsonResponse
from django.test import Client
from django.urls import path

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


def add_to_cart(request, item):
    cart = request.session.get("cart", [])
    cart.append(item)
    request.session["cart"] = cart                      # assignment marks the session as modified
    response = JsonResponse({"cart": cart})
    response.set_cookie("theme", "dark", max_age=3600, httponly=True, samesite="Lax")
    return response


urlpatterns = [path("add/<str:item>/", add_to_cart)]

c = Client()
print(c.get("/add/notebook/").json())
print(c.get("/add/pen/").json())
print(sorted(c.cookies.keys()))
print(c.cookies["sessionid"]["httponly"], c.cookies["theme"]["samesite"])
print(Session.objects.count(), "session row in the database")
print(list(Session.objects.get().get_decoded().items()))
other = Client()
print(other.get("/add/ruler/").json())                  # a new visitor starts with a new session

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 sessions table is created with the schema editor; a real project runs migrate. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {'cart': ['notebook']} {'cart': ['notebook', 'pen']} ['sessionid', 'theme'] True Lax 1 session row in the database [('cart', ['notebook', 'pen'])] {'cart': ['ruler']}

Key points

  • Cookies live in the browser; sessions hold data on the server
  • Only a random session ID is sent in the cookie
  • Backends: db, cache, cached_db, files, signed_cookies
  • Set Secure, HttpOnly and SameSite flags
  • login() rotates the key; flush() on logout

Common mistakes

  • Storing passwords or tokens in plain cookies
  • Using signed_cookies for sensitive or large data
  • Forgetting clearsessions, so django_session grows forever
  • Mutating a nested object in the session without reassigning it

Follow-ups

  • Why does Django not encrypt signed cookie sessions?
  • How would you log a user out of all devices?
  • When is a JWT better than a session?

Tips

  • Contrast browser-held and server-held data
  • Name two backends
  • Mention cookie flags
59.django-0059Easyfresher

How does validation work on Django models: field validators, clean() and full_clean(), and why does save() not validate?

Field validators and clean()/clean_fields()/validate_unique() run when you call full_clean(), which ModelForms and the admin call for you. Model.save() does not call full_clean(), so writing through the ORM or a custom view skips validation unless you call it. Database constraints are the last line of defence because they always apply.

Full answer

Three layers check data:

  1. Field-level: max_length, null, choices, and validators=[...] such as MinValueValidator(0), RegexValidator or your own function that raises ValidationError.
  2. Model-level: override clean() for rules that involve several fields, and raise ValidationError({"end": "End must be after start"}) to attach the error to a field.
  3. Database-level: UniqueConstraint, CheckConstraint, NOT NULL, foreign keys.

full_clean() runs clean_fields(), then clean(), then validate_unique() and validate_constraints(), and raises a single ValidationError holding all messages (exc.message_dict). ModelForm and the admin call it, so form submissions get friendly errors.

save() does not call it, because validation costs queries and not every write needs it. Code such as Student.objects.create(score=-5) happily writes bad data if only Python validators protect it. Therefore:

  • Call obj.full_clean() before save() in your own services, or validate through a Form or serializer.
  • Put hard invariants in CheckConstraint so the database rejects bad rows, and bulk operations or raw SQL cannot bypass it.
  • blank=True is validation-only (can the form be empty); null=True is a database setting. Text fields normally use blank=True without null=True.

Validators run in migrations as part of the field definition, so keep validator functions importable at module level (not lambdas or local 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.core.exceptions import ValidationError
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models, connection, IntegrityError


class Exam(models.Model):
    title = models.CharField(max_length=30)
    marks = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)])
    start = models.IntegerField()
    end = models.IntegerField()

    class Meta:
        app_label = "school"
        constraints = [models.CheckConstraint(condition=models.Q(marks__gte=0), name="marks_not_negative")]

    def clean(self):
        if self.end <= self.start:
            raise ValidationError({"end": "End must be after start."})


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

bad = Exam(title="Unit test", marks=150, start=10, end=5)
try:
    bad.full_clean()
except ValidationError as exc:
    print(exc.message_dict)

Exam(title="Quiz", marks=150, start=1, end=2).save()           # save() does not validate
print("saved marks:", Exam.objects.get().marks)

try:
    Exam.objects.create(title="Broken", marks=-1, start=1, end=2)
except IntegrityError as exc:
    print("database refused:", type(exc).__name__)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. CheckConstraint uses condition=, the keyword since Django 5.1 (check= was removed in 6.0). Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {'marks': ['Ensure this value is less than or equal to 100.'], 'end': ['End must be after start.']} saved marks: 150 database refused: IntegrityError

Key points

  • Validators run in full_clean(), not in save()
  • clean() handles cross-field rules
  • ValidationError can be attached to a field via a dict
  • CheckConstraint enforces rules for every write path
  • blank is for validation, null is for storage

Common mistakes

  • Assuming save() or create() runs validators
  • Relying on validators alone for invariants that must always hold
  • Using null=True on CharField instead of blank=True
  • Using lambdas as validators, which cannot be serialised in migrations

Follow-ups

  • How do ModelForms report errors from clean()?
  • What does validate_constraints() do?
  • How do you validate in a DRF serializer instead?

Tips

  • Say which method calls what
  • Point out the database as final defence
  • Distinguish blank and null
60.django-0060Easyfresher

How do you paginate a long list in Django using Paginator, and what are the page object's useful attributes?

Paginator(queryset, per_page) splits a sequence into pages. paginator.get_page(number) returns a Page object that safely falls back to the first or last page for invalid input, with attributes such as object_list, has_next(), has_previous(), number and paginator.num_pages. Always paginate an ordered queryset, and be aware that very large OFFSET values get slow.

Full answer
python
paginator = Paginator(Student.objects.order_by("name"), per_page=10)
page = paginator.get_page(request.GET.get("page"))

get_page() never raises: a missing, non-numeric or out-of-range page number returns page 1 or the last page. The older page() raises PageNotAnInteger and EmptyPage.

Useful members:

  • paginator.count (total rows), paginator.num_pages, paginator.page_range.
  • page.object_list, iteration over the page, page.number.
  • page.has_next(), page.next_page_number(), page.has_previous().
  • paginator.get_elided_page_range(number) gives a compact list like 1 2 … 9 10 11 … 20 for UI links.

Pitfalls:

  • Unordered querysets give unstable pages (rows can repeat or vanish), and Django warns with UnorderedObjectListWarning.
  • count runs SELECT COUNT(*) on every request. On huge tables this dominates; cache the count or use cursor-based (keyset) pagination, which filters with WHERE id > last_seen ORDER BY id LIMIT n.
  • Deep OFFSET (page=50000) forces the database to skip rows.
  • Generic ListView supports paginate_by = 10 and puts page_obj and paginator in the template context.

In templates, build links with ?page={{ page_obj.next_page_number }} and keep other query parameters (filters) in the URL.

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.paginator import Paginator, EmptyPage
from django.db import models, connection


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

    class Meta:
        app_label = "school"


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

Student.objects.bulk_create(Student(name=f"S{i:02d}") for i in range(1, 24))
p = Paginator(Student.objects.order_by("name"), per_page=10)

page = p.get_page(2)
print(page.number, [s.name for s in page][:3], page.has_next(), page.has_previous())
print(p.count, p.num_pages, list(p.page_range))
print(p.get_page("abc").number, p.get_page(99).number, p.get_page(None).number)
try:
    p.page(99)
except EmptyPage as exc:
    print("EmptyPage:", exc)

last_seen = "S10"                                              # keyset pagination: no OFFSET
nxt = Student.objects.filter(name__gt=last_seen).order_by("name")[:3]
print([s.name for s in nxt])

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): 2 ['S11', 'S12', 'S13'] True True 23 3 [1, 2, 3] 1 3 1 EmptyPage: That page contains no results ['S11', 'S12', 'S13']

Key points

  • get_page() is forgiving; page() raises for bad numbers
  • Order the queryset before paginating
  • count() query runs per request
  • Keyset pagination scales better than OFFSET
  • ListView has paginate_by

Common mistakes

  • Paginating an unordered queryset
  • Using page() with raw request input and crashing on bad values
  • Using OFFSET pagination for millions of rows
  • Dropping filter parameters from the pagination links

Follow-ups

  • What is keyset pagination and its trade-offs?
  • How would you avoid the COUNT query?
  • How does DRF's PageNumberPagination relate to Paginator?

Tips

  • Mention get_page vs page
  • Warn about ordering
  • Name keyset pagination