Django Interview Questions
Q: What is Django's MTV architecture?
Model-Template-View. Model defines data structure (ORM). Template is the HTML layer (Django template language or Jinja2). View is the business logic — processes requests and returns responses (equivalent to Controller in MVC). Django's "View" is closer to a controller; the "Template" is the view in MVC terms.
Q: What is the N+1 query problem and how does Django address it?
If you have 100 posts and access post.author for each, Django issues 101 queries. Fix with select_related() for ForeignKey/OneToOne (performs a SQL JOIN) and prefetch_related() for ManyToMany and reverse ForeignKey (issues separate optimized query). Use django-debug-toolbar to detect N+1 issues.
Q: What is the difference between FBV and CBV?
Function-Based Views (FBV) are simple Python functions — easy to understand, explicit. Class-Based Views (CBV) provide inheritance and mixins for code reuse — ListView, DetailView, CreateView, etc. handle common patterns. CBVs reduce boilerplate for CRUD but are harder to understand initially. DRF ViewSets extend CBV further for APIs.
Q: How do Django migrations work?
makemigrations compares the current models to previous migrations and generates a new migration file. migrate applies pending migration files to the database. Django tracks applied migrations in the django_migrations table. Migrations support forward and backward (rollback) operations. Always commit migration files to version control.
Q: What is Django's middleware?
Middleware is a layer of processing applied to every request/response. It's a hook system for adding behaviors globally: authentication, sessions, CSRF protection, security headers, GZIP compression. Middleware is configured in settings.MIDDLEWARE as an ordered list — request processing is top-to-bottom, response is bottom-to-top.
Q: What is CSRF and how does Django protect against it?
Cross-Site Request Forgery tricks users into making unintended requests using their authenticated session. Django's CsrfViewMiddleware generates a unique token per session, requires it in all POST/PUT/DELETE requests, and rejects requests without a valid token. For APIs using token auth (JWT), CSRF is less of a concern since tokens aren't sent automatically by browsers.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free