Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 77 ยท Practice and Review

Django Interview Questions

43 Django interview questions with answers on MTV, the ORM, migrations, middleware, signals, security, performance and async, with runnable examples.

A Django interview usually tests three things: whether you understand how a request becomes a response, whether you can use the ORM without hurting performance, and whether you know the framework's safety features well enough to avoid common security and design mistakes. This page collects 43 questions that come up again and again, grouped by topic, with short answers you can expand in your own words.

Try to answer each question out loud before opening it. If you cannot explain an idea in two or three sentences, follow the link to the lesson and review it. Five questions come with live editors so you can check the behavior yourself, which is the best way to remember it.

Tip: in a real interview, a short, correct answer plus a tiny example beats a long recital. Mention trade-offs ("select_related is one query but a wider row; prefetch_related is two queries but no duplication") and what you would measure. That is what separates mid-level answers from junior ones.

Framework basics

What is Django, and what does "batteries included" mean?

Django is a high-level Python web framework that ships the parts most sites need: URL routing, an ORM, templates, forms, authentication, an admin interface, sessions, caching, internationalization and security protections. "Batteries included" means you rarely need third-party packages for the basics, and the pieces are designed to work together. See the introduction.

Explain the MTV pattern and how it compares with MVC.

Django's Model describes data and talks to the database, the Template renders presentation, and the View is the Python code that receives a request and returns a response. In MVC terms, the Django view plays the controller, the template plays the view, and the framework's URL dispatcher is the front controller that routes requests.

What is the difference between a project and an app?

A project is the whole website: settings, root URL configuration and deployment entry points (manage.py, wsgi.py, asgi.py). An app is a self-contained package of related functionality (models, views, templates, tests) that is listed in INSTALLED_APPS. One project contains many apps, and a well-designed app can be reused in other projects. See Projects, Apps and Settings.

Describe the life of a request in Django.

The web server hands the request to Django through WSGI or ASGI. Django builds an HttpRequest, runs it through the middleware chain, resolves the URL against urlpatterns to find a view, and calls the view. The view returns an HttpResponse, which travels back out through the middleware (in reverse order) to the server. See The Request and Response Cycle.

What are WSGI and ASGI?

Both are standards for how a Python web application talks to a web server. WSGI is synchronous: one request at a time per worker. ASGI supports async code, WebSockets and long-lived connections. Django supports both: wsgi.py and asgi.py are generated by startproject. You deploy WSGI with Gunicorn or uWSGI and ASGI with Uvicorn, Daphne or Hypercorn.

What does manage.py do, and what are the commands you use most?

It is a thin wrapper around django-admin that sets DJANGO_SETTINGS_MODULE for your project. Common commands: runserver, makemigrations, migrate, createsuperuser, shell, test, collectstatic, check (use check --deploy before releases) and your own custom commands.

URLs and views

When would you choose a class-based view over a function-based view?

Class-based views (CBVs) shine when you want reuse and structure: generic views such as ListView or CreateView remove boilerplate, and mixins add behavior like login or permission checks. Function-based views (FBVs) are simpler to read when the logic is unusual or short. Neither is "better"; many projects mix both. See Class-Based Views.

Why use reverse() and {% url %} instead of hard-coded paths?

Named URLs decouple links from the path layout. If you change /blog/<slug>/ to /articles/<slug>/, every reverse("post-detail", args=[slug]) and {% url "post-detail" slug %} keeps working. Namespaces (app_name) prevent clashes between apps that use the same URL names. See URL Routing.

What is the difference between request.GET and request.POST?

request.GET holds the query-string parameters and request.POST holds form-encoded body data of a POST request. Both are QueryDict objects, which can hold several values per key (getlist). A JSON body is in neither: read request.body and parse it yourself. Uploaded files are in request.FILES. See Request Data.

How do you return a 404 for a missing object?

Use get_object_or_404(Model, pk=pk) or raise Http404. With DEBUG = False, Django renders your 404.html template (or the built-in page). A common mistake is using Model.objects.get() without handling DoesNotExist, which becomes a 500 error.

The ORM

Are QuerySets lazy? What does that mean?

Yes. Building a queryset (filter, exclude, order_by) runs no SQL. The query executes when you iterate, slice with a step, call len(), list(), bool(), repr(), or methods such as count(), exists() or get(). Once evaluated, a queryset caches its results, so iterating it again does not hit the database. Try it below.

Python Lazy evaluation and result caching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What is the difference between select_related and prefetch_related?

Both fight the N+1 problem. select_related follows forward ForeignKey and OneToOneField relations using a SQL JOIN in a single query. prefetch_related runs a separate query per relation and joins the results in Python, which makes it the right choice for reverse foreign keys and many-to-many fields. Use Prefetch(...) to filter or order the prefetched rows. See ORM Performance.

What is the N+1 query problem and how do you find it?

It is one query to fetch a list plus one more query per item to fetch something related, so the query count grows with the data. Find it with django-debug-toolbar, CaptureQueriesContext, query logging, or a test using assertNumQueries. Fix it with select_related, prefetch_related or annotate. See Common Django Mistakes.

What is the difference between filter(), exclude() and get()?

filter() and exclude() return a queryset (possibly empty). get() returns exactly one object and raises DoesNotExist when nothing matches or MultipleObjectsReturned when more than one does. Use filter(...).first() when "none" is a normal outcome.

What are Q and F objects for?

Q builds conditions that need OR or NOT (Q(a=1) | ~Q(b=2)) and lets you compose filters dynamically. F refers to a column's value inside the database, for comparisons between fields (filter(sold__gt=F("stock"))) and atomic updates (update(views=F("views") + 1)), which avoid race conditions that read-modify-write code has. See Lookups, Q Objects and F Expressions.

What is the difference between annotate() and aggregate()?

aggregate() collapses a queryset into one dictionary ({"avg_price": ...}). annotate() adds a computed attribute to each object, which gives you "group by" behavior when combined with values(). Annotations can be filtered and ordered on. See Aggregation and Annotation.

How do values(), values_list() and only() differ?

values() returns dictionaries and values_list() returns tuples (or flat values), with no model instances, which is lighter. only() and defer() still return model instances but load just some columns; touching a deferred field triggers an extra query. The editor after this section shows the shapes.

How do you do many writes efficiently?

Use bulk_create() and bulk_update() instead of a save() loop, and QuerySet.update() for one statement that changes many rows. Remember that these skip save() and signals. Wrap related writes in transaction.atomic().

What does transaction.atomic() do, and what is ATOMIC_REQUESTS?

atomic() runs a block in a database transaction: if the block raises an exception, all its writes are rolled back. Nested blocks become savepoints. Setting ATOMIC_REQUESTS = True wraps every view in a transaction. Use transaction.on_commit() to run side effects (such as sending an e-mail) only after a successful commit. See Transactions and Concurrency.

What is a custom manager, and why add methods to a QuerySet?

A manager (Model.objects) is the interface for queries. Custom QuerySet methods (exposed with as_manager() or from_queryset) put reusable, chainable filters in one place, such as Article.objects.published().by_author(user), so views stay thin. See Custom Managers.

How do you run raw SQL safely?

Use Model.objects.raw("... WHERE name = %s", [name]) or connection.cursor().execute(sql, params) and always pass values as parameters, never with string formatting. The driver escapes parameters, which prevents SQL injection. Prefer the ORM, and use raw SQL only for things it cannot express.

The next editor shows the day-to-day ORM idioms that interviewers love to ask about.

Python get_or_create, update_or_create and values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

get_or_create returns a (object, created) pair and relies on a unique constraint to stay safe under concurrency. update_or_create updates the object with defaults or creates it. in_bulk fetches many objects into a dictionary with one query.

Migrations

What do makemigrations and migrate do?

makemigrations compares your models with the migration history and writes new migration files describing the change. migrate applies unapplied migrations to the database and records them in the django_migrations table. Use sqlmigrate to preview the SQL and showmigrations to see the state. See Migrations.

What is a data migration, and when do you need one?

A migration that changes data instead of schema, written with RunPython (give it a reverse function when possible). Use it to backfill a new column or convert values. Inside it, get models with apps.get_model() rather than importing them, because the real model may have changed since.

How do you resolve conflicting migrations?

When two branches each add a migration depending on the same parent, the graph has two leaf nodes. Pull the other changes, run makemigrations --merge, review the generated merge migration and commit it. Better: communicate about schema changes and run migrate before creating new migrations.

Is it safe to edit or delete a migration that has been applied?

No. Others (and production) have already recorded it as applied, so editing it makes environments diverge. Add a new migration instead. You may squash old migrations with squashmigrations once every environment is past them.

Middleware and signals

What is middleware, and in what order does it run?

Middleware is a chain of hooks that wrap request processing, used for sessions, authentication, CSRF protection, security headers and more. For the request, middleware runs top to bottom through MIDDLEWARE; for the response, bottom to top. Order matters: AuthenticationMiddleware needs SessionMiddleware above it. The editor below traces the flow.

Python Middleware order, process_view and process_exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the trace as an onion: outer wraps inner, which wraps the view. process_view runs just before the view, and process_exception runs when the view raises, which lets a middleware turn an exception into a response. See Middleware.

What are signals, and what are the downsides?

Signals let one piece of code announce an event (post_save, pre_delete, m2m_changed, or your own) and let other code react without the sender knowing about it. The downsides: hidden control flow, no guaranteed order, and they do not fire for bulk_create() or QuerySet.update(). Prefer explicit function calls for your own business logic. See Signals.

Python post_save and a custom signal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The created flag tells a receiver whether the save inserted or updated a row. Signal.send() returns a list of (receiver, response) pairs; send_robust() catches exceptions raised by receivers instead of stopping.

Forms and templates

What is the difference between Form and ModelForm?

A Form declares fields by hand and is not tied to the database. A ModelForm generates fields from a model, applies its validators and has save(). Use Form for things like search boxes or contact forms; use ModelForm for creating and editing records. See ModelForms.

How does form validation work?

is_valid() runs each field's clean() (type conversion and validators), then any clean_<fieldname>() method, then the form-level clean(). Problems become ValidationErrors collected in form.errors, and valid data ends up in form.cleaned_data. See Form Validation.

Explain template inheritance.

A base template defines {% block %} sections; child templates {% extends "base.html" %} and override those blocks (calling {{ block.super }} to keep the parent's content). It removes duplicated headers and footers. {% include %} inserts a reusable fragment. See Template Inheritance.

What is autoescaping, and when is |safe dangerous?

Django's template engine HTML-escapes every variable by default (< becomes &lt;), which blocks most cross-site scripting. |safe, {% autoescape off %} and mark_safe() switch that off for a value, so use them only for HTML you generated yourself, never for user input.

Security and authentication

How does Django protect against CSRF, XSS and SQL injection?

CSRF: CsrfViewMiddleware rejects unsafe requests (POST, PUT, DELETE) that lack a valid token, which forms include with {% csrf_token %}. XSS: templates autoescape variables. SQL injection: the ORM always passes values as query parameters. The editor below demonstrates all three. See Security in Django.

Python XSS, SQL injection and CSRF in 30 lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The f-string version returns both rows, so an attacker who controls attack could read data they should not see. The parameterized query and the ORM treat the whole string as a harmless value. The test client skips CSRF checks by default; enforce_csrf_checks=True turns them on so you can test the protection.

Why should you create a custom user model at the start of a project?

Changing AUTH_USER_MODEL after tables and foreign keys exist is painful because migrations and relations already point at the old model. Even if you just subclass AbstractUser with no changes, you keep the option to add fields later. See Custom User Models.

How does Django store passwords?

It never stores the plain password. make_password() produces a string with the algorithm, a random salt, the iteration count and the hash (PBKDF2 by default, with Argon2 and others available through PASSWORD_HASHERS). check_password() verifies a candidate, and hashes are upgraded transparently when settings change.

How do sessions work?

The browser keeps a session id in a cookie; the data lives on the server (database by default, or cache, files or signed cookies). request.session behaves like a dictionary. Set SESSION_COOKIE_SECURE and SESSION_COOKIE_HTTPONLY in production. See Sessions and Cookies.

What is the difference between authentication and authorization in Django?

Authentication answers "who are you?" (authenticate(), login(), request.user). Authorization answers "what may you do?" (permissions, groups, has_perm, login_required, PermissionRequiredMixin, and per-object checks you write yourself). See Permissions.

Performance, async and production

What can you do to make a slow Django page fast?

Measure first (query count and time, a profiler or the debug toolbar). Then: fix N+1 queries, add database indexes for filtered and ordered columns, load fewer columns and rows (only, pagination), cache expensive results (per-view, template-fragment or low-level cache), move slow work to background workers, and put a CDN in front of static files. See Performance and Scaling and Caching.

How does caching work in Django?

You configure a backend in CACHES (local memory for development, Redis or Memcached in production) and use the cache API (cache.get, cache.set, cache.get_or_set), the @cache_page decorator, or the {% cache %} template tag. Choose sensible timeouts and decide how to invalidate: delete keys when data changes or version them.

Does Django support async?

Yes. You can write async def views and run Django under ASGI. The ORM has async methods (aget, acreate, acount, async for) that run the database work in a thread pool, and sync_to_async / async_to_sync bridge between worlds. Async helps when a view spends its time waiting on network calls; for plain database-bound pages it often adds little. Never call blocking code (a sync ORM query, time.sleep) directly inside an async view. See Async Django. A small sketch:

Python
from django.http import JsonResponse

async def dashboard(request):
    total = await Order.objects.acount()
    latest = [o async for o in Order.objects.order_by("-id")[:5]]
    return JsonResponse({"total": total, "latest": [o.pk for o in latest]})

This code is read-only here because the browser runtime has no thread pool for the async ORM bridge.

How do you run background tasks?

Anything slow or unreliable (e-mail, report generation, calls to third-party APIs) should not run inside the request. Use a task queue such as Celery with Redis or RabbitMQ, or a lighter alternative; newer Django versions also include a task framework interface. Make tasks idempotent and pass ids, not objects. See Docker, Celery and CI.

How do you serve static files in production?

Set STATIC_ROOT, run collectstatic, and let a web server, a CDN or WhiteNoise serve the collected files. Django's development server serves static files only when DEBUG is on. Uploaded files (MEDIA_ROOT) need object storage or a web-server rule. See Static Files and Media and Deploying Django.

What is the difference between TestCase and SimpleTestCase?

SimpleTestCase blocks database access and is fast. TestCase wraps each test in a transaction that is rolled back afterwards and offers setUpTestData for class-level fixtures. TransactionTestCase truncates tables instead and is used when you test transaction behavior itself. See Testing Django Apps.

What would you check before deploying a Django site?

DEBUG = False, a secret SECRET_KEY from the environment, a correct ALLOWED_HOSTS, HTTPS settings (SECURE_SSL_REDIRECT, HSTS, secure cookies), a production database, collectstatic, logging and error reporting, backups, and a passing python manage.py check --deploy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does a QuerySet actually run its SQL?

    QuerySets are lazy: building and chaining them only constructs a query. Evaluation triggers the SQL, and the results are then cached on that queryset object.
  2. 2. Which tool is the right fit for a reverse foreign key or many-to-many relation when fixing an N+1 problem?

    prefetch_related runs an extra query for the related rows and attaches them in Python. select_related uses a JOIN and is meant for forward ForeignKey and OneToOne relations.
  3. 3. With MIDDLEWARE = [A, B], in what order does the response pass through the middleware?

    Requests go down the list (A then B then the view). The response travels back up (B then A), like layers of an onion.
  4. 4. Why is building SQL with an f-string dangerous?

    Values inserted into the SQL text can contain quotes and keywords. Passing them as separate parameters lets the driver treat them strictly as data.
  5. 5. Which statement about signals is true?

    save() sends pre_save and post_save. update() and bulk_create() bypass save(), and receiver order should not be relied upon.

Summary

  • Know the request path: server, WSGI/ASGI, middleware, URL resolver, view, response, and MTV roles.
  • QuerySets are lazy and cached; fix N+1 with select_related (JOIN) and prefetch_related (extra query).
  • Use F for atomic database-side updates, Q for OR/NOT, annotate per object and aggregate for one summary.
  • Migrations are history: add new ones, merge conflicts, never rewrite applied ones.
  • Middleware runs top to bottom on the way in and bottom to top on the way out; signals are convenient but implicit.
  • Django defends against CSRF, XSS and SQL injection by default, if you do not switch the defenses off.
  • For speed, measure first, then fix queries, add indexes and caches and move slow work to background tasks.

Next lesson: Django Cheat Sheet.