Skip to content
>_ StartupJobList_

Interview questions · Worked answers

Django interview questions and production answers

Follow each request from query construction to response and database commit. Explain what fails under a replay, competing write, rollback, disconnect, or old/new deployment overlap.

For: Backend engineers building tenant-aware Django applications

Guide scope and versions

Django 5.2 LTS, specifically the 5.2.18 package release; behavior follows Django 5.2 documentation. Database locking, isolation, DDL and migration behavior depend on the selected backend. The runnable body uses synthetic SQLite and makes no PostgreSQL locking claim.

Question 1 of 10

When does a QuerySet actually read the database?

Iterating, converting to a list, truth-testing with bool(), and calling len() evaluate a queryset and populate its result cache when it is not already populated. With no populated cache, exists() and count() issue optimized queries without filling that cache; with a cache, they can answer from the cached results. iterator() streams without using the normal result cache.

A view assigns open_orders = Order.objects.filter(tenant=tenant, state="open"). Building it runs no query. First normal iteration runs SQL and fills that queryset’s result cache; iterating that same instance can reuse it. Calling bool(open_orders) also evaluates and caches the result set when it is uncached. By contrast, uncached exists() and count() issue optimized SQL without filling the full result cache, while iterator() streams without that cache. If a write occurs between those uncached calls, they may observe newer rows, subject to transaction isolation.

Explain whether slicing avoids evaluation. A slice without a step generally remains a queryset with LIMIT/OFFSET; a stepped slice evaluates to a list. Calling bool(qs) evaluates and caches the full result set, while exists() is preferable for a presence check. Use a fresh queryset when the caller needs a new query; transaction isolation is a separate database contract.

Follow-up: Does queryset caching mean later reads are fresh?

No. The evaluated instance reuses its result cache; construct a new query when freshness is required, and define transaction/isolation needs separately.

Read the source: QuerySet evaluation · Query optimization

↑ Back to questions

Question 2 of 10

How do you remove an N+1 query without overfetching?

Use select_related() for single-valued foreign-key/one-to-one paths and prefetch_related() for many-valued relations. Eager loading changes query shape and memory, not access policy.

A page emits 40 reservations with each product name and adjustment rows. Join the product with select_related("product"); fetch adjustments in a separate bounded prefetch. A join across a many-valued relation can multiply parent rows. Filtering the prefetched manager differently can miss the prefetch cache, and prefetch materializes related rows in memory.

A strong answer names the serializer fields first, chooses exact paths, and checks query count and result size on representative limits. Do not prefetch an unbounded history just to quiet a query counter.

Follow-up: What if only the newest adjustment is required?

Use an explicitly bounded ordered query or current-state field; fetching all adjustment history is not justified.

Read the source: QuerySet relations · Database optimization

↑ Back to questions

Question 3 of 10

Where should tenant scope enter a Django query?

Apply tenant scope in the base queryset before selecting an object, and derive detail lookups from that scoped queryset. A later permission check is still needed, but unscoped retrieval creates avoidable disclosure and accidental-use paths.

Unsafe: Reservation.objects.get(pk=reservation_id) followed by a tenant comparison. Safer: get_object_or_404(Reservation.objects.filter(tenant=request.tenant), pk=reservation_id). The out-of-scope ID and nonexistent ID can share a 404 policy. Scope nested child queries, exports, bulk updates, and background jobs independently; scoping a parent does not scope every subsequent query.

A complete answer tests a valid foreign-tenant identifier against read, update, delete, nested, and bulk routes. Database row-level security can add a boundary on supported systems, but needs its own setup and proof.

python / Django 5.2.18 · Worked example
from django.conf import settings

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

import django

django.setup()

from django.db import IntegrityError, connection, models


class Reservation(models.Model):
    tenant = models.CharField(max_length=8)
    request_key = models.CharField(max_length=8)
    sku = models.CharField(max_length=8)
    quantity = models.PositiveIntegerField()

    class Meta:
        app_label = "proof"
        constraints = [
            models.UniqueConstraint(
                fields=["tenant", "request_key"],
                name="tenant_request_once",
            )
        ]


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

Reservation.objects.create(
    tenant="T-7", request_key="R-1", sku="SKU-9", quantity=2
)
assert Reservation.objects.filter(tenant="T-7", request_key="R-1").count() == 1
assert Reservation.objects.filter(tenant="T-8", request_key="R-1").count() == 0

try:
    Reservation.objects.create(
        tenant="T-7", request_key="R-1", sku="SKU-9", quantity=2
    )
except IntegrityError:
    pass
else:
    raise AssertionError("duplicate tenant/request key was accepted")

assert Reservation.objects.count() == 1

Creates only an in-memory SQLite schema and synthetic rows. It proves ORM tenant filtering and that the declared tenant/request-key uniqueness constraint rejects a duplicate without adding a row. It does not prove an API returns a previous response, concurrent behavior, row locks, or PostgreSQL behavior.

Django 5.2.18 example; tenant-filtered ORM query and unique constraint on fresh in-memory SQLite; no concurrency or PostgreSQL-locking claim.

Follow-up: Is a 404 an authorization control?

It limits existence disclosure on that route. It does not replace authorization on all access paths or prove database-level isolation.

Read the source: QuerySet filtering · Authentication and permissions

↑ Back to questions

Question 4 of 10

Can `save()` or `full_clean()` guarantee stock never goes negative?

No. Application validation improves errors; database constraints protect invariants against competing requests and alternate writers. Use a conditional update or backend-supported locking for the state transition.

Two workers read stock 3 and each reserve 2. Both pass Python validation, then can overwrite a stale value. Add a CheckConstraint for nonnegative stock and update conditionally (filter(stock__gte=n).update(stock=F("stock")-n)); one updated row means success. A unique tenant/idempotency key handles replay. Translate IntegrityError only after leaving the failed atomic block.

select_for_update() can serialize inspect-then-change flows inside a transaction on a supporting database. Keep lock order stable and still retain declarative constraints. SQLite cannot prove PostgreSQL lock behavior.

Follow-up: When is a row lock appropriate?

When a decision must inspect then mutate rows and the selected engine supports row locks. State the backend and isolation assumptions; do not infer them from SQLite tests.

Read the source: Constraints · F expressions · select_for_update

↑ Back to questions

Question 5 of 10

What survives when a nested `atomic()` block fails?

Nested atomic blocks normally create savepoints. A caught exception leaving the inner block rolls back to that savepoint while prior outer work can continue; an exception escaping the outer block rolls back the whole transaction.

For a 100-row import where one duplicate should be skipped, put each risky insert in a nested atomic() and catch IntegrityError outside that inner block. Catching it before Django exits the broken transaction can make later SQL fail. Translate only the named expected conflict; surface other integrity errors.

Disabling savepoints removes the local recovery boundary. It can only be considered when measured and no row-level recovery is needed.

Follow-up: Does savepoint=False preserve per-row recovery?

No. It removes the savepoint; the outer transaction can be marked failed.

Read the source: Transactions and savepoints

↑ Back to questions

Question 6 of 10

What does `transaction.on_commit()` guarantee for notifications?

It invokes a callback only after commit, so a rolled-back write does not send a notification. It does not persist delivery intent; process death between commit and callback can lose the notification, and callback failure cannot undo the commit.

A reservation commits and an on_commit callback publishes an event, then the process exits. Reservation state is committed; the event may never have been attempted. For durable delivery, write an outbox row in the same transaction and publish it idempotently with retries. on_commit can wake the publisher, while polling/recovery handles a missed wakeup.

Keep client-visible reservation state separate from notification state. A callback exception is an operational delivery failure, not a failed reservation.

python / Django 5.2.18 · Worked example
from django.conf import settings

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

import django

django.setup()

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


class Entry(models.Model):
    key = models.CharField(max_length=8, unique=True)

    class Meta:
        app_label = "proof"


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

seen = []
with transaction.atomic():
    Entry.objects.create(key="kept")
    try:
        with transaction.atomic():
            Entry.objects.create(key="duplicate")
            transaction.on_commit(lambda: seen.append("rolled-back"))
            Entry.objects.create(key="duplicate")
    except IntegrityError:
        pass
    transaction.on_commit(lambda: seen.append("committed"))
    assert seen == []

assert list(Entry.objects.values_list("key", flat=True)) == ["kept"]
assert seen == ["committed"]

Uses only a fresh in-memory SQLite table. It asserts savepoint rollback and on_commit callback ordering for this synthetic transaction. It does not prove external message durability or PostgreSQL concurrency.

Django 5.2.18 example; nested savepoint rollback and on_commit ordering on fresh in-memory SQLite; no durable external-delivery claim.

Follow-up: Can a failed callback roll back the database commit?

No. The callback runs after commit. Persist delivery intent transactionally when the message is required.

Read the source: on_commit

↑ Back to questions

Question 7 of 10

Can middleware rewrite every response through `response.content`?

No. StreamingHttpResponse lacks a materialized content attribute and may be large or unbounded. A wrapper must preserve lazy iteration and match sync/async iterator type.

Footer middleware works for JSON but fails on a streamed CSV. Branch on response.streaming. For a stream, lazily transform each chunk without consuming the iterator first; if the transformation needs the complete document, use a bounded materialized response instead.

A client disconnect can stop iteration after partial bytes have been sent. Do not assume the response can be retried transparently; close owned resources and use cursor/resume semantics where needed.

Follow-up: Can streamed bytes be rolled back after a disconnect?

No. Bytes already sent are observable; define resumability and idempotent source behavior separately.

Read the source: Streaming middleware · StreamingHttpResponse

↑ Back to questions

Question 8 of 10

How should an async view perform a transactional ORM operation?

Django 5.2 provides async variants for many ORM operations, but transactions are not supported in async mode. Put the complete transaction-dependent unit in one synchronous function and bridge it once with sync_to_async.

An async view awaits an initial queryset, reads an unloaded relation, then enters atomic(). Relation access can trigger sync I/O and raise SynchronousOnlyOperation; atomic is also unsupported in async ORM mode. Move the read/validate/write unit into one sync helper, eager-load the needed relation, and call it across one adapter boundary.

Repeatedly bridging individual rows adds context switches and may split intended transaction ownership.

Follow-up: Does ASGI eliminate sync middleware cost?

No. Adaptation can hold a thread for exception propagation; measure the actual middleware stack, especially for long-lived I/O.

Read the source: Async support · Async queries

↑ Back to questions

Question 9 of 10

How do you rename a column while old and new workers overlap?

Use expand-and-contract: add a compatible field, deploy code able to read/write both, backfill bounded resumable batches, verify, switch readers, then remove the old field after old workers and rollback paths are gone.

For warehouse_code to location_code, add the new column first; dual-write or backfill through code compatible with both schemas. Track batch progress and verify equality/completeness before switching reads. Remove the old column only in a later release. Analyze lock/rewrite behavior against the selected engine and table size.

Use migration-state historical models via apps.get_model(); current models may have drifted since migration creation. A one-step rename/drop can break old jobs still running during deploy.

Follow-up: Can migration completion prove a safe production rollout?

No. It proves the migration command completed on its target database; rollout overlap, lock duration, backfill completeness, and rollback must be separately observed.

Read the source: Writing migrations · Operations

↑ Back to questions

Question 10 of 10

When is an authenticated Django POST still unsafe?

Authentication names the caller; object authorization permits the state change. Cookie-authenticated browser writes also need CSRF protection. Validate redirect destinations and user-controlled output at their own boundaries.

A logged-in operator posts a reservation ID, new tenant ID, and next URL. Require authorization for that reservation and destination, do not trust tenant identity from the form, keep CSRF validation, and restrict redirects to trusted local targets.

Test invalid cross-tenant transitions. A valid session does not authorize every object or prevent cross-site request forgery.

Follow-up: When may CSRF be exempted?

Only for a deliberately different reviewed authentication model with appropriate origin/replay controls, not to silence a failing test.

Read the source: Security · CSRF

↑ Back to questions

Salary context

Advertised salaries for these skills

These are Hacker News job posts that mention these technologies, not employee earnings or a measure of what a skill adds to pay. The amounts summarize annualized advertised minimums in approximate USD. Groups can overlap and differ in roles, locations and dates.

Django posts

52 posts · 52 usable advertised salary amounts

2024-07-02 to 2026-11-04

$130,000

Median advertised minimum, approximate USD/year

Middle 50%: $93,792–$150,000

Explore Django salaries → Browse matching job posts →
Currency and calculation basis

Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged Django, rather than every job in the broader technology family.

↑ Back to questions

Keep exploring