Django interview questions and answers for Python developers

Django interview questions focus on the ORM: when a queryset actually hits the database, how to spot and fix N+1 queries with select_related and prefetch_related, and how migrations change a live schema. Expect follow-ups on middleware, signals, authentication, Django REST Framework and the security protections Django turns on for you. Strong answers name the query count, the transaction boundary or the setting involved instead of describing Django in general terms.

By Published 9 min read

How Django shows up in interviews

Django is tested in Python backend loops, full-stack roles at companies whose product runs on it, and data-heavy teams that use its admin and ORM for internal tools. A job titled Django developer usually means three rounds that touch the framework: a concept screen, a practical task (build or extend a small API, often with Django REST Framework), and a deeper conversation about a slow endpoint or a data bug. General backend rounds on design and APIs are covered in backend developer interview questions.

  1. Concept screenTwenty to forty minutes of short questions: MVT, querysets, migrations, middleware, what CSRF protection does.
  2. Take-home or live buildA small app with models, a few endpoints and tests. Reviewers read your models and query patterns before your views.
  3. Code review or debuggingA view that runs hundreds of queries, a migration that locks a table, a signal that fires twice. You explain the cause and the fix.
  4. Design and experienceHow you structure apps in a large project, background jobs, caching and how you deploy safely.

Django fundamentals questions

First-round questions for freshers and experienced developers
QuestionWhat it testsWhat a strong answer shows
What is MVT and how does it map to MVC?ArchitectureThe model holds data and rules, the view is the Python function or class that handles a request, the template renders output. Django's view plays the controller role; the URLconf routes to it.
Project versus app?StructureA project is the deployment: settings, root URLconf, WSGI or ASGI entry. An app is a reusable package of models, views and migrations listed in INSTALLED_APPS.
Walk through a request from URL to response.Request cycleThe server hands the request to the WSGI or ASGI handler, middleware runs in order, the URL resolver picks a view, the view returns a response, and middleware runs again in reverse on the way out.
What is the difference between null=True and blank=True?Model fieldsnull controls the database column (allows NULL). blank controls validation in forms and the admin. For text fields, Django's convention is an empty string rather than NULL.
get() versus filter()?Querysetsget returns one object and raises DoesNotExist or MultipleObjectsReturned. filter returns a queryset, possibly empty, and never raises for zero rows.
What does on_delete do on a ForeignKey?IntegrityIt decides what happens to rows pointing at a deleted parent: CASCADE deletes them, PROTECT blocks the delete, SET_NULL clears the link, and so on. Picking CASCADE everywhere is how an admin click deletes a customer's history.
Function-based or class-based views?ViewsFunction views are explicit and easy to read. Class-based and generic views remove repetition for list, detail and form pages but hide the flow in mixins. Say when you would choose each.
Static files versus media files?FilesStatic files ship with the code (CSS, JS) and are collected with collectstatic. Media files are user uploads stored under MEDIA_ROOT or object storage and must never be trusted as code.
What does DEBUG=True change, and why must it be off in production?SettingsIt shows detailed error pages with settings and local variables and serves static files in development. In production it leaks internals; ALLOWED_HOSTS must also be set.
What is the admin good for, and what is it not?JudgmentFast internal CRUD for staff with permissions. It is not a customer-facing UI, and large tables need list_select_related, search fields and pagination to stay usable.
First-round questions for freshers and experienced developers. Scroll sideways on a small screen.

ORM and queryset questions

This is where Django interviews are won or lost. A queryset is lazy: building it with filter, exclude or order_by runs no SQL. The query runs when the queryset is evaluated, for example by iterating, slicing with a step, calling len() or list(), or testing it in an if. The results are then cached on that queryset object, so iterating the same object twice queries once.

# models: Book has author = ForeignKey(Author) and tags = ManyToManyField(Tag)

# N+1: one query for the books, then one more per book for its author
for book in Book.objects.all():
    print(book.title, book.author.name)

# One query: the author comes back in the same row through a JOIN
for book in Book.objects.select_related("author"):
    print(book.title, book.author.name)

# Two queries: the books, then every tag for those books in one IN (...) query
for book in Book.objects.prefetch_related("tags"):
    print(book.title, [tag.name for tag in book.tags.all()])
The N+1 problem and its two fixes. With five books, the first loop ran six queries, the second one and the third two.
  • When do you use select_related and when prefetch_related? select_related follows forward ForeignKey and one-to-one links with a SQL join. prefetch_related handles many-to-many and reverse foreign keys with a second query and joins the results in Python. A join on a many-to-many would multiply rows.
  • How do you find N+1 queries before production? django-debug-toolbar in development, assertNumQueries in tests so a regression fails the build, and query logging or an APM tool in staging. Mention that serializers and templates are the usual hiding places.
  • What is an F expression? A reference to a column's value inside the database. update(stock=F("stock") - 1) makes the database do the arithmetic in one statement, which avoids a read-modify-write race in Python.
  • What are Q objects for? Combining conditions with OR, AND and NOT, for example Q(status="open") | Q(assignee=user), which keyword arguments to filter cannot express alone.
  • annotate versus aggregate? aggregate returns one dictionary for the whole queryset (a total). annotate adds a computed value to each row, such as a count of books per author, and can then be filtered or ordered.
  • values, values_list, only and defer? values and values_list return dictionaries or tuples instead of model instances, cheaper for reports. only and defer still return instances but load fewer columns; touching a deferred field later triggers another query.
  • exists() or count() or len()? Use exists() to ask whether any row matches, count() for a number without loading rows, and len() only when you are about to use the rows anyway.
  • How do you process a million rows without running out of memory? iterator() with a chunk size streams rows without filling the queryset cache, and bulk_create or bulk_update write in batches. Note that bulk operations skip save() and signals.

Migrations, middleware, signals and auth

Intermediate questions
QuestionWhat it testsWhat a strong answer shows
makemigrations versus migrate?Migrationsmakemigrations writes migration files from model changes; migrate applies them to the database and records them in the django_migrations table. Migration files are code and go through review.
How do you add a non-nullable column to a large live table?Safe schema changeAdd it nullable or with a default, backfill in batches with a data migration or a script, then add the constraint in a later deploy. Know whether your database rewrites the table for that change.
What is a data migration?RunPythonA migration that changes rows, not schema, using apps.get_model for the historical model rather than importing the current one, with a reverse function where possible.
Two branches both added migration 0007. Now what?ConflictsDjango detects two leaf nodes. Run makemigrations --merge or renumber one branch, and check that the two migrations do not touch the same fields.
How does middleware order matter?MiddlewareRequests pass through the list top to bottom and responses bottom to top. Session middleware must come before authentication, which needs the session to find the user.
When would you use a signal, and when not?SignalsGood for decoupled reactions such as clearing a cache when a model saves. Poor for core business logic because the flow becomes invisible, and bulk updates do not send them.
Why set a custom user model at the start of a project?AuthSwapping AUTH_USER_MODEL after the first migrations is painful because foreign keys already point at auth.User. Starting with a subclass of AbstractUser costs nothing.
Authentication versus authorization in Django?AuthAuthentication identifies the user (sessions, backends). Authorization decides what they may do: permissions, groups, has_perm, and object-level checks you write yourself.
Form versus ModelForm, and where does validation live?FormsA ModelForm builds fields from a model. Validation runs through field cleaning, then clean_<field>, then clean(); model constraints are the last line of defense in the database.
Intermediate questions. Scroll sideways on a small screen.
import time


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

    def __call__(self, request):
        start = time.perf_counter()
        response = self.get_response(request)  # the next middleware, then the view
        elapsed_ms = (time.perf_counter() - start) * 1000
        response["Server-Timing"] = f"app;dur={elapsed_ms:.1f}"
        return response
A small middleware: code before get_response runs on the way in, code after it on the way out.

Security defaults questions

  • What does CSRF protection do and when do you exempt a view? The middleware checks a token on unsafe methods for cookie-authenticated requests. Exempt only endpoints that do not use cookie sessions, such as a webhook verified by signature.
  • How does Django prevent SQL injection, and how can you break that? The ORM parameterizes values. You reintroduce the risk with string formatting inside raw(), extra() or cursor.execute; pass parameters separately instead.
  • How are templates protected from XSS? Variables are autoescaped. The risk returns with the safe filter, mark_safe on user input, or rendering untrusted HTML in JavaScript.
  • What else is on by default? Clickjacking protection through X-Frame-Options, password hashing with a slow algorithm, and host header validation through ALLOWED_HOSTS. manage.py check --deploy lists settings to tighten, such as secure cookies and HSTS.
  • Where does SECRET_KEY live? In the environment or a secret manager, never in the repository. It signs sessions, password reset tokens and messages, so a leak means rotating it.

Django REST Framework questions

from rest_framework import serializers

from .models import Book


class BookSerializer(serializers.ModelSerializer):
    author_name = serializers.CharField(source="author.name", read_only=True)

    class Meta:
        model = Book
        fields = ["id", "title", "author", "author_name"]

    def validate_title(self, value):
        if len(value) < 3:
            raise serializers.ValidationError("Title is too short.")
        return value
A ModelSerializer with a read-only field taken from the related author and a field validator.
  • What does a serializer do? It converts model instances to primitive data for the response and validates incoming data before saving, much like a form does for HTML.
  • Why can the serializer above cause N+1 queries? author.name is read per book. The view's queryset should use select_related("author"), which is the fix interviewers want to hear.
  • APIView, generic views or ViewSets? APIView for custom flows, generic views for standard CRUD on one model, ViewSets with a router when you want the full set of routes generated.
  • Authentication, permissions and throttling? Authentication classes identify the caller (session, token, JWT through a package), permission classes allow or deny, and throttles limit request rates per user or IP.
  • How do you paginate a large list? Page-number pagination is simple; cursor pagination stays fast and stable on large, changing tables because it avoids big offsets.

Senior Django and scenario questions

Scenarios interviewers describe
ScenarioLikely causeWhat to say you would check
A list endpoint got slow as data grew.N+1 or missing indexCount queries per request, add select_related or prefetch_related, check EXPLAIN for sequential scans on filtered columns, and paginate.
Stock sometimes goes negative under load.Read-modify-write raceReplace the Python decrement with a conditional F() update, or lock the row with select_for_update inside transaction.atomic.
An email goes out for an order that was rolled back.Side effect inside a transactionSend it with transaction.on_commit, or hand it to a task queue only after the commit.
A post_save handler runs twice or not at all.Signal wiringDuplicate registration (connect in ready() with a dispatch_uid) or a code path using update() or bulk_create, which sends no signal.
A migration took the site down.Table lockA column change that rewrote or locked a large table. Split it into additive steps and run backfills outside the migration.
Memory spikes in a nightly export.Queryset cacheUse iterator() and values_list, write rows as you go, and avoid building one list of every instance.
Scenarios interviewers describe. Scroll sideways on a small screen.
from django.db import transaction
from django.db.models import F

from .models import Product


def sell_one(product_id):
    # One UPDATE statement; the database does the arithmetic, so two
    # requests at the same moment cannot both read 1 and both write 0.
    updated = Product.objects.filter(pk=product_id, stock__gt=0).update(stock=F("stock") - 1)
    return updated == 1


def sell_many(product_id, qty):
    with transaction.atomic():
        product = Product.objects.select_for_update().get(pk=product_id)
        if product.stock < qty:
            return False
        product.stock -= qty
        product.save(update_fields=["stock"])
    return True
Two ways to sell stock safely. The first is one UPDATE; the second locks the row for a multi-step check.
  • WSGI or ASGI? WSGI servers handle one request per worker thread or process. ASGI allows async views, websockets through Channels and long-lived connections. Async views only help when the work inside them is truly async; sync ORM calls in an async view need sync_to_async.
  • Where do background jobs go? A task queue such as Celery or RQ with a broker. Tasks should be idempotent, take IDs rather than model instances, and be retried with backoff.
  • How do you cache in Django? Per-view caching, template fragment caching, and the low-level cache API around expensive queries, with a clear invalidation rule. Redis or Memcached as the backend.
  • How do you organize a project with fifty models? Apps by business domain, thin views, query logic in managers or service functions, and no circular imports between apps.

Fictional example

Answering "This orders page takes four seconds. What do you do?"
Interviewer
An internal page lists 200 orders with the customer name and the items on each order. It takes four seconds. Walk me through it.
Candidate
I would measure before touching anything: debug toolbar or query logging to get the query count and the slowest statement. With that shape of page my first guess is N+1, one query for orders, then one per order for the customer and one per order for the items, so roughly 400 extra queries. The fix is select_related for the customer, since that is a forward foreign key, and prefetch_related for the items, since that is a reverse relation. That should bring it to two or three queries. If the remaining query is still slow I would run EXPLAIN on it and check for an index on the filter and sort columns. Then I would add an assertNumQueries test so the page cannot quietly regress.

Django practice plan

  • Day 1: build two related models and a list page, open the debug toolbar, and watch the query count change as you add select_related and prefetch_related.
  • Day 2: write a data migration with a reverse function, then practice adding a required column in three safe steps.
  • Day 3: add a DRF endpoint with a serializer, a permission class and cursor pagination, and test it with APIClient.
  • Day 4: reproduce a stock race with two threads, then fix it with F() and with select_for_update and explain the difference.
  • Day 5: run check --deploy on a project and explain each warning out loud, then do a timed mock of the concept screen.

Django sits inside broader loops. Pair this page with Flask interview questions for the lighter framework comparison, PL/SQL interview questions if the role works against an Oracle database, and software engineer interview questions for the general coding rounds.

Query-count answers are easy to fumble when you say them out loud. Natively, an AI interview assistant for Mac and Windows, transcribes a mock Django round on your computer so you can check afterward whether you named select_related or just said "optimize the query". During practice it can read a view or a traceback from a screenshot and suggest code, and with Pro or the free trial it can use the résumé and job description you add. Transcripts and notes stay saved so you can review them.

Questions people ask

What Django questions are asked in interviews?

Expect MVT and the request cycle, lazy querysets, select_related versus prefetch_related, migrations, middleware order, signals, the custom user model, Django REST Framework serializers and Django's built-in protections such as CSRF and autoescaping.

What is the difference between select_related and prefetch_related?

select_related follows foreign key and one-to-one links with a SQL join in the same query. prefetch_related runs a second query for many-to-many or reverse relations and joins the results in Python.

How do I prepare for a Django developer interview?

Build a small app with related models and an API, watch the query count as you optimize it, write a safe data migration, and practice explaining transactions, race conditions and the security settings out loud.

Are Django REST Framework questions part of a Django interview?

For API roles, usually. Expect serializers and validation, ViewSets and routers, authentication and permission classes, pagination and how a serializer can trigger N+1 queries.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP