Technology

Django Interview Questions and Answers

Django is a batteries-included Python web framework used by many startups and enterprises. These Django interview questions cover MVT, models, views, templates and the admin for freshers, then the ORM, migrations, middleware, Django REST Framework, query optimisation, security and deployment for experienced Django developers.

30 questions · Updated

Reading answers is not the same as saying them.Practise Django questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AI
Django Interview Questions with answers. Examples: What is Django, and what is the MVT architecture? What is the difference between a project and an app in Django? What are migrations? What is the difference between select_related and prefetch_related?
Django Interview Questions: 30 questions with model answers on this page.

Basic Django interview questions

Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.

1. What is Django, and what is the MVT architecture?

Answer flow · 3 steps
  1. Django is a high-level Python web framework that includes an ORM, admin panel, authentication, forms, templating and security features out of the box.

  2. It follows Model-View-Template: models define data and database tables, views contain the logic that handles requests and returns responses, and templates render HTML.

  3. Django itself acts as the controller, routing URLs to views.

2. What is the difference between a project and an app in Django?

Answer flow · 3 steps
  1. A project is the whole website with its settings, root URL configuration and WSGI or ASGI entry point.

  2. An app is a self-contained module for one feature, such as blog, accounts or payments, with its own models, views, URLs and templates.

  3. A project contains several apps, and apps can be reused across projects.

3. What are migrations?

Migrations are files that record changes to models so the database schema can be updated to match. makemigrations creates migration files from model changes, and migrate applies them to the database. They are version-controlled, so every environment can be brought to the same schema, and can include data migrations.

4. What is the Django ORM, and why are QuerySets lazy?

Answer flow · 3 steps
  1. The ORM lets you work with the database using Python classes and methods instead of SQL, for example Book.objects.filter(published=True).order_by("-created").

  2. A QuerySet is lazy: building and chaining filters does not touch the database until you iterate over it, slice it, call len(), list() or similar.

  3. This lets Django build one efficient query from all the chained conditions.

5. How do you define relationships between models?

Answer flow · 3 steps
  1. ForeignKey creates a many-to-one relationship, such as many books to one author, with on_delete deciding what happens when the author is deleted (CASCADE, PROTECT, SET_NULL).

  2. ManyToManyField links many to many, such as books and tags, using a join table, optionally a custom one with through.

  3. OneToOneField links exactly one to one, such as a user and a profile. related_name sets the reverse accessor.

6. What is the Django admin?

Answer flow · 3 steps
  1. The admin is an automatically generated interface for managing data in registered models.

  2. With a ModelAdmin class you configure list_display, list_filter, search_fields, inlines for related objects, read-only fields and custom actions.

  3. It is ideal for internal staff and content management, but is not meant as a customer-facing interface.

7. How does URL routing work in Django?

urls.py files map URL patterns to views with path(), using converters such as <int:id> or <slug:slug> to capture values, and include() to delegate to each app's URL configuration. Naming routes, as in path("books/<int:pk>/", views.detail, name="book-detail"), lets you build URLs with reverse() or the url template tag instead of hard-coding them.

8. How does template inheritance work?

Answer flow · 3 steps
  1. A base template defines the common layout with {% block content %}{% endblock %} placeholders.

  2. Child templates start with {% extends "base.html" %} and override only the blocks they need. {% include %} inserts reusable fragments, and custom template tags and filters add logic.

  3. The template language deliberately limits logic so that it stays in views.

9. What is the difference between Form and ModelForm?

Answer flow · 3 steps
  1. A Form defines fields and validation for any input, such as a contact form.

  2. A ModelForm builds its fields automatically from a model, validates them against the model's rules and can save directly to the database with form.save().

  3. Both clean and validate data, show errors, and protect against CSRF when rendered with {% csrf_token %}.

10. Which settings in settings.py are most important?

DEBUG (must be False in production), SECRET_KEY (from the environment), ALLOWED_HOSTS, DATABASES, INSTALLED_APPS, MIDDLEWARE, TEMPLATES, STATIC_URL and STATIC_ROOT, MEDIA settings, AUTH_USER_MODEL, TIME_ZONE and USE_TZ, and security settings such as CSRF_TRUSTED_ORIGINS and SECURE_SSL_REDIRECT. Many projects split settings by environment or read them from environment variables.

11. What is the difference between static files and media files?

Answer flow · 3 steps
  1. Static files are part of the code, such as CSS, JavaScript and images, collected into STATIC_ROOT with collectstatic and served by WhiteNoise, Nginx or a CDN.

  2. Media files are uploaded by users, such as profile photos, stored in MEDIA_ROOT or cloud storage such as S3 through django-storages.

  3. Django should not serve either directly in production.

Intermediate Django interview questions

Applied problems, trade-offs and questions about your own projects.

12. What is the difference between select_related and prefetch_related?

Both solve the N+1 query problem. select_related follows foreign key and one-to-one relationships using an SQL JOIN, fetching related objects in the same query. prefetch_related runs a separate query for each relationship and joins the results in Python, which works for many-to-many and reverse foreign key relationships.

13. What is middleware in Django?

Answer flow · 4 steps
  1. Middleware is a layer of hooks that process every request and response globally.

  2. Each middleware can act before the view runs, after it returns, or on exceptions.

  3. Built-in middleware handles sessions, authentication, CSRF protection, security headers and messages.

  4. Order in the MIDDLEWARE setting matters because requests pass through top to bottom and responses bottom to top.

14. What is the difference between function-based and class-based views?

Function-based views are simple functions that take a request and return a response, which is explicit and easy for simple logic. Class-based views organise handling by HTTP method and allow reuse through inheritance and mixins, and generic views such as ListView, DetailView and CreateView handle common patterns with very little code.

15. What are Django signals, and when would you avoid them?

Answer flow · 3 steps
  1. Signals let code react to events, such as post_save after a model is saved or user_logged_in, without the sender knowing about the receiver.

  2. They are useful for decoupled apps, such as creating a profile when a user is created.

  3. I avoid overusing them because the flow becomes hidden and hard to debug; explicit service functions are usually clearer.

16. What are F and Q objects?

F() refers to a field's value in the database, so you can compare fields or update a value without loading it, such as Product.objects.update(stock=F("stock") - 1), which avoids race conditions. Q() builds complex conditions with OR (|), AND (&) and NOT (~), such as filter(Q(city="Pune") | Q(city="Mumbai")).

17. What is the difference between aggregate and annotate?

aggregate() calculates values over the whole QuerySet and returns a dictionary, such as Order.objects.aggregate(total=Sum("amount")). annotate() adds a calculated value to each object, such as Author.objects.annotate(book_count=Count("books")), which you can then filter or sort on. Both run the calculation in the database, which is far faster than looping in Python.

18. Why should you create a custom user model?

Answer flow · 3 steps
  1. Changing the user model after the first migration is very difficult, so Django recommends starting every project with a custom user model, usually subclassing AbstractUser, and setting AUTH_USER_MODEL.

  2. It lets you add fields such as phone number or log in with email instead of username later.

  3. Code should refer to the user with get_user_model() or settings.AUTH_USER_MODEL.

19. How do authentication and permissions work in Django?

Answer flow · 4 steps
  1. django.contrib.auth provides users, password hashing, login and logout views, sessions, groups and permissions.

  2. Views are protected with @login_required or LoginRequiredMixin, and @permission_required or PermissionRequiredMixin check model permissions such as "blog.change_post".

  3. Groups assign permissions to many users.

  4. Object-level permissions need custom checks or a library such as django-guardian.

20. What are custom managers and QuerySets?

Answer flow · 3 steps
  1. A manager is the interface to database queries for a model, objects by default.

  2. A custom QuerySet class holds reusable, chainable query methods, such as Post.objects.published().recent(), and is attached with as_manager() or a custom manager.

  3. This keeps query logic in one place instead of repeating filters across views.

21. How do you use database transactions in Django?

By default each query is committed immediately. transaction.atomic, as a decorator or context manager, wraps several operations so they all succeed or all roll back, for example creating an order and reducing stock. select_for_update locks rows to prevent concurrent changes, and transaction.on_commit runs code such as sending emails only after the transaction has committed.

22. How does Django's caching framework work?

Answer flow · 3 steps
  1. Django supports cache backends such as Redis, Memcached, the database and local memory.

  2. You can cache whole pages with the cache_page decorator, fragments of templates with {% cache %}, or any value with the low-level API (cache.get, cache.set).

  3. Cache keys must include anything the result depends on, such as the user or language, and entries need sensible timeouts or invalidation.

High level Django interview questions

System design, deep internals, leadership and tough follow-ups.

23. How do you build an API with Django REST Framework?

Answer flow · 3 steps
  1. I define serializers to convert models to JSON and validate input, use ViewSets or generic API views for endpoints, and register them with routers for URLs.

  2. I configure authentication (session, token or JWT), permission classes, pagination, filtering and throttling.

  3. Query optimisation in get_queryset with select_related and prefetch_related keeps endpoints fast.

24. How do you optimise a slow Django application?

I use Django Debug Toolbar or django-silk to find slow views and duplicate queries, fix N+1 problems with select_related and prefetch_related, fetch only needed columns with only() or values(), add database indexes, and use aggregate and annotate to calculate in the database. I cache expensive results with Redis, paginate large lists, and move slow tasks to Celery.

25. What security features does Django provide?

Answer flow · 3 steps
  1. Django protects against SQL injection through the ORM, cross-site scripting through automatic template escaping, cross-site request forgery with CSRF tokens, and clickjacking with the X-Frame-Options header.

  2. It hashes passwords with PBKDF2 by default and supports argon2.

  3. In production I set DEBUG = False, use a secret key from the environment, set ALLOWED_HOSTS, enable HTTPS settings such as SECURE_SSL_REDIRECT and secure cookies, and run manage.py check --deploy.

26. How do you run background tasks in Django?

Answer flow · 3 steps
  1. Celery with Redis or RabbitMQ as the broker runs tasks such as sending emails, generating reports and processing images in worker processes, with retries, scheduling through celery beat, and monitoring with Flower.

  2. Simpler alternatives include RQ and Dramatiq, and Django 6.0 adds a built-in tasks framework.

  3. Tasks should be idempotent and receive IDs rather than whole objects.

27. What are ASGI, async views and Django Channels?

Answer flow · 4 steps
  1. ASGI is the asynchronous successor to WSGI.

  2. Django supports async def views, async ORM methods and async middleware, which help with views that wait on external APIs.

  3. Django Channels adds WebSockets and other long-lived connections, for chat or live updates, using a channel layer such as Redis to communicate between processes.

  4. Servers such as Uvicorn or Daphne run ASGI apps.

28. How do you deploy a Django application?

Run it with Gunicorn (or Uvicorn for ASGI) behind Nginx or a cloud load balancer with HTTPS, set DEBUG = False and read secrets from the environment, run migrations and collectstatic during deployment, serve static files with WhiteNoise or a CDN and media from cloud storage, use PostgreSQL, add Redis for caching and Celery, and set up logging, error tracking with Sentry and backups. Containers make this repeatable.

29. How do you test a Django project?

Django's TestCase wraps each test in a transaction and provides a test client for requests; pytest-django gives the same with pytest fixtures. factory_boy builds test data, APIClient tests Django REST Framework endpoints, and assertNumQueries catches N+1 problems. External calls are mocked, and tests run in CI with a real PostgreSQL database.

30. How do you scale the database layer of a large Django app?

Add indexes for common filters and orderings (Meta.indexes), avoid N+1 queries, use only(), defer(), values() and iterator() for large datasets, and move heavy reports to raw SQL or database views. Add connection pooling with PgBouncer or Django 5.1's built-in pooling for PostgreSQL, send reads to replicas with database routers, cache aggressively, and partition very large tables.

Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.
Start a mock interview

Preparing for a backend developer interview?

See all Backend Developer interview questions, covering Node.js, Express.js, NestJS, Python, Django and more.

Related skill interview questions

More technology interview questions

HR round, company and bank interview questions

Bank and government exams

Interview questions for other fields