Django Interview Questions and Answers (Django 5)
Last updated 2026-11-19
Django interviews lean heavily on the ORM, because that is where most real bugs and slow pages come from. Expect questions on how querysets are evaluated, how to avoid N+1 queries, how migrations behave on a live database, and how the framework protects you against CSRF and injection. This page works through those with Django 5 behaviour in mind.
Django 5 added database-computed fields, default values at the database level and a few form and admin improvements, and Django 5.1 added a login-required middleware. These are called out where relevant. For Python language questions, see how to crack a Python interview, and for general API and database design read the backend developer questions.
| Version covered | Django 5.x on Python 3.10 and later |
|---|---|
| Core topics | ORM, migrations, views, middleware, security, DRF, async |
| Questions here | 17 |
How the ORM questions are framed
A typical prompt shows a view that loops over objects and touches a related field, and asks why it is slow. The answer is to count queries: use django-debug-toolbar or connection.queries in a test, then apply select_related for foreign keys and one-to-one fields, or prefetch_related for many-to-many and reverse relations. Knowing when each query actually runs, because querysets are lazy, is the other half.
Django 5 additions to know
- db_default on a field sets a default in the database schema itself, not only in Python.
- GeneratedField defines a column computed by the database from other columns.
- Facets in the admin changelist show filter counts.
- Field group rendering helpers simplify form templates.
- Django 5.1 added LoginRequiredMiddleware, making every view require login unless marked otherwise.
Django Interview Questions and Answers (Django 5): questions with worked answers
1 Explain Django's MTV architecture and the request flow.
easyDjango uses Model, Template and View, where the view plays the role a controller plays in MVC. A request enters through middleware, the URL resolver matches a pattern to a view, the view queries models and returns an HttpResponse, usually rendering a template, and the response passes back through middleware in reverse order. Settings, apps and the ORM sit behind this pipeline.
2 What does it mean that QuerySets are lazy?
easyBuilding a queryset with filter or exclude does not hit the database. The query runs only when you iterate, slice with a step, call list, len, bool, count, or otherwise evaluate it. Results are cached on the queryset after the first evaluation, so iterate the same object twice and only one query runs. Use exists() instead of bool and count() instead of len when you do not need the rows.
pythonqs = Book.objects.filter(price__lt=500) # no query yet qs = qs.order_by("title") # still none if qs.exists(): # one cheap query first_ten = list(qs[:10]) # LIMIT 103 What is the N+1 problem, and how do select_related and prefetch_related differ?
mediumAccessing a related object inside a loop issues one query per row. select_related follows foreign keys and one-to-one fields with a SQL JOIN, giving a single query. prefetch_related runs a second query for the related table and joins in Python, which is the way to handle many-to-many and reverse foreign keys. Prefetch objects let you filter or annotate the prefetched set.
pythonfrom django.db.models import Prefetch books = (Book.objects .select_related("author") # JOIN .prefetch_related(Prefetch("reviews", queryset=Review.objects.filter(rating__gte=4))))4 How do F and Q objects help?
mediumF refers to a column value inside the database, so Book.objects.update(stock=F("stock") - 1) runs one UPDATE statement and avoids a read-modify-write race. Q lets you build OR, AND and NOT conditions that the keyword-only filter syntax cannot, combined with |, & and ~.
pythonfrom django.db.models import F, Q Product.objects.filter(pk=pk).update(stock=F("stock") - 1) User.objects.filter(Q(is_staff=True) | Q(email__endswith="@corp.in"), ~Q(is_active=False))5 How do migrations work and what are the risks on a live database?
mediummakemigrations compares your models with the migration history and writes a migration file. migrate applies unapplied ones and records them in django_migrations. Risks: adding a NOT NULL column without a default fails or locks big tables, renaming looks like drop and add, and a long migration blocks deploys. Use two-step changes, db_default or a nullable column first, RunPython for data backfills, and never edit applied migrations.
6 When do you use transaction.atomic and select_for_update?
mediumatomic wraps a block so all writes commit together or roll back on exception. Django runs in autocommit by default, and ATOMIC_REQUESTS wraps each request in a transaction. select_for_update locks the selected rows until the transaction ends, so concurrent workers cannot both claim the same row. It needs to run inside atomic and works only on databases that support row locks.
pythonfrom django.db import transaction with transaction.atomic(): acct = Account.objects.select_for_update().get(pk=pk) acct.balance -= amount acct.save(update_fields=["balance"])7 What is middleware and how do you write one?
mediumMiddleware is a hook into the request and response processing. A middleware class receives get_response in its initialiser and implements __call__, running code before the view and after the response. Order in the MIDDLEWARE setting matters: SecurityMiddleware first, then sessions, CSRF and authentication. Use it for cross-cutting work such as request IDs and timing.
pythonclass TimingMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): start = time.perf_counter() response = self.get_response(request) response["X-Elapsed-ms"] = str(int((time.perf_counter() - start) * 1000)) return response8 Function-based or class-based views?
mediumFunction-based views are explicit and simple to read. Class-based views, such as ListView or DetailView, reuse behaviour through mixins and reduce boilerplate for CRUD, at the cost of indirection. Pick whichever keeps the code clear. Django REST framework adds APIView and viewsets, with routers that generate URL patterns for you.
9 How does Django protect against common attacks?
mediumTemplates auto-escape output to prevent XSS. The ORM parameterises queries, so injection is avoided unless you use raw SQL with string formatting. CsrfViewMiddleware requires a token on unsafe methods. Clickjacking is blocked with X-Frame-Options, and security settings such as SECURE_SSL_REDIRECT, HSTS and secure cookies handle transport. Never set DEBUG to True in production and set ALLOWED_HOSTS. See web security and OWASP questions.
10 What are Django signals and when should you avoid them?
mediumSignals such as post_save let decoupled code react to events. They are handy for cross-app hooks, but make flow hard to follow, run inside the same transaction and are skipped by bulk_create and queryset update. For logic that belongs to the model, override save or write a service function, and use transaction.on_commit to trigger tasks only after a successful commit.
11 How do you design a custom user model, and why decide early?
mediumSubclass AbstractUser, or AbstractBaseUser for full control, and set AUTH_USER_MODEL before the first migration. Changing it later is painful because foreign keys and migrations already reference the default user table. Reference the user through settings.AUTH_USER_MODEL or get_user_model() rather than importing the class.
12 How do you add constraints and indexes in Django 5?
mediumDeclare them in Meta. UniqueConstraint with condition gives partial uniqueness, CheckConstraint enforces rules in the database, and Index with fields speeds queries. Constraints use the database for enforcement, so they protect against races that a Python validation cannot. In Django 5.1 CheckConstraint uses the condition argument.
pythonclass Booking(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) start = models.DateTimeField() end = models.DateTimeField() class Meta: constraints = [models.CheckConstraint(condition=models.Q(end__gt=models.F("start")), name="end_after_start")] indexes = [models.Index(fields=["room", "start"])]13 What does GeneratedField do in Django 5?
hardGeneratedField creates a database column whose value the database computes from an expression over other columns, kept in sync automatically. With db_persist=True it is stored, and it is read-only in Django. It suits derived values such as a full name or line total that you want to index and filter on without extra code. Check your database for supported modes.
pythonclass LineItem(models.Model): qty = models.PositiveIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) total = models.GeneratedField( expression=models.F("qty") * models.F("price"), output_field=models.DecimalField(max_digits=12, decimal_places=2), db_persist=True, )14 How does async work in Django 5?
hardViews can be defined with async def and run under ASGI, and the ORM exposes async methods such as aget, acreate and async iteration. Under WSGI an async view runs in an event loop per request, so it gains little. Calling synchronous ORM code from async code raises SynchronousOnlyOperation, so use the a-prefixed methods or sync_to_async. Async helps for concurrent external calls, not for CPU work.
15 How do you cache in Django?
hardConfigure a backend such as Redis in CACHES. Use the low-level cache API for computed values, cache_page for whole views, template fragment caching, and per-site middleware. The hard part is invalidation: key by object version or delete on save, set sensible timeouts, and avoid caching per-user pages under a shared key. Use cache.get_or_set to keep code simple.
16 How do you handle long-running work such as sending email or reports?
hardMove it out of the request cycle to a task queue such as Celery with Redis or RabbitMQ, or a database-backed queue, and respond immediately. Pass IDs rather than objects, make tasks idempotent because they may run twice, and enqueue with transaction.on_commit so the worker does not see a row that has not committed yet. Django 6 adds a built-in tasks framework interface, but a worker backend is still required.
17 How do you write a serializer and viewset in Django REST framework?
hardA ModelSerializer maps model fields to JSON and validates input, with validate_ methods for field rules. A ModelViewSet gives list, create, retrieve, update and destroy, and a router wires up the URLs. Set permission_classes and authentication, add pagination and filtering, and override get_queryset to scope data to the requesting user, which prevents insecure direct object references.
pythonclass BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ["id", "title", "price", "author"] class BookViewSet(viewsets.ModelViewSet): serializer_class = BookSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Book.objects.filter(owner=self.request.user).select_related("author")
Frequently asked questions
Is Django still in demand?
Yes. Django is widely used for web backends, content platforms and internal tools, and Python backend job postings frequently list Django or Flask.
Which Django version should I know?
Django 5.x, the current line, plus the 4.2 LTS behaviour, because plenty of production systems remain on it. Mention what is new in 5.
Do I need Django REST framework for interviews?
For backend roles, yes: serializers, viewsets, permissions and pagination are commonly asked.
What is the best way to practise?
Build a small app with a custom user, a few related models, an API and tests, then profile its queries and fix any N+1 problems you find.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- Docker Interview Questions and Answers
- Ethical Hacking Interview Questions and Answers
- ETL and Data Warehousing Interview Questions and Answers
- Excel Interview Questions and Answers
- Express.js Interview Questions and Answers (Express 5)
- FastAPI Interview Questions and Answers
- Flask Interview Questions and Answers
- Flutter Interview Questions and Answers (Flutter 3, Dart 3)
- Frontend Developer Interview Questions and Answers
- Full Stack Developer Interview Questions and Answers
- Generative AI and LLM Interview Questions and Answers
- Google Cloud (GCP) Interview Questions and Answers