{jsonbody.com}

Top 50 Django Interview Questions & Answers

Get ready for Django interviews with 50 answers on the ORM, select_related, migrations, signals, Django REST Framework, security and deployment.

Django Fundamentals

Q1. What is Django?

Django is a high-level Python web framework that includes an ORM, admin site, authentication, forms, templates and security features, so common web features work without extra packages.

Q2. What is the MVT pattern?

Django separates Models for data, Views for request logic and Templates for presentation. The framework's URL routing connects each request to the right view.

Q3. What is the difference between a project and an app?

A project is the whole site, with its settings and root URLs. An app is a reusable module for one feature, and a project can contain many apps.

Q4. What happens during a Django request?

The request passes through middleware to the URL resolver, which calls a view. The view returns a response, often using models and templates, which then passes back through middleware.

Q5. What is the difference between path() and re_path()?

path() uses simple route patterns and converters, as in users/<int:id>/. re_path() uses regular expressions for more complex matching.

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

Function-based views are simple and explicit. Class-based views organize HTTP methods into a class and support reuse through inheritance and mixins.

Q7. What are generic views?

Prebuilt class-based views such as ListView, DetailView and CreateView that handle common patterns with little code.

Q8. What is middleware?

Middleware is a chain of hooks around every request and response. Authentication, sessions, CSRF checks and security headers all use it, and its order in MIDDLEWARE matters.

Q9. What is template inheritance?

A base template defines shared layout with {% block %} tags, and child templates use {% extends %} to override those blocks. This avoids repeating page structure.

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

Static files such as CSS and JavaScript belong to the code, and collectstatic gathers them for deployment. Media files are uploaded by users and are stored separately.

Models & ORM

Q11. What is the Django ORM?

It maps Python classes to database tables and lets you query with Python rather than SQL. It works with several databases and uses parameterized queries by default.

Q12. Are QuerySets lazy?

Yes. Building a QuerySet runs no SQL until it is evaluated, for example by iterating, slicing with a step, or calling list(). Filters can therefore be chained cheaply.

Q13. What is the difference between select_related and prefetch_related?

select_related uses a SQL JOIN for foreign key and one-to-one fields. prefetch_related runs a separate query and joins in Python, which suits many-to-many and reverse relations.

Q14. What is the N+1 query problem in Django?

It occurs when one query loads a list and each item triggers another query for related data. Fix it with select_related or prefetch_related, and check queries with Django Debug Toolbar.

Q15. What is the difference between filter() and get()?

filter() returns a QuerySet of zero or more rows. get() returns one object and raises DoesNotExist or MultipleObjectsReturned if it does not find exactly one.

Q16. What are F and Q objects?

F refers to a column value in the database, enabling updates such as F("stock") - 1 without loading the row. Q builds complex conditions using |, & and ~.

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

aggregate() returns one summary across the QuerySet as a dictionary. annotate() adds a calculated value to each row, such as a count of related records.

Q18. What do the on_delete options do?

They control what happens when a referenced row is deleted. CASCADE deletes dependents, PROTECT and RESTRICT block deletion, and SET_NULL or SET_DEFAULT replace the reference.

Q19. What types of model inheritance does Django have?

Abstract base classes share fields without their own table. Multi-table inheritance creates a linked table per model. Proxy models change behaviour without adding fields or tables.

Q20. How do you make bulk operations efficient?

Use bulk_create and bulk_update for many rows, and QuerySet.update() for a single SQL update. They skip custom save() methods and, usually, signals, so check for side effects.

Migrations, Transactions & Signals

Q21. What is the difference between makemigrations and migrate?

makemigrations creates migration files from model changes. migrate applies those files to the database and records which ones have run.

Q22. How do you resolve conflicting migrations?

Conflicts occur when branches create separate migrations from the same parent. Use makemigrations --merge when the changes are compatible, and review the result.

Q23. What is a data migration?

A migration that changes data rather than schema, usually with RunPython. It should use apps.get_model() for the historical model, and should provide reverse logic when possible.

Q24. What is squashmigrations?

It combines a range of migrations into fewer files, which speeds up test and setup runs on long-lived projects.

Q25. How do you run schema changes with no downtime?

Split risky changes into steps: add a nullable column, deploy code that writes to both columns, backfill in batches, switch reads, then remove the old column in a later release.

Q26. How do transactions work in Django?

Django runs in autocommit mode by default. Wrap related writes in transaction.atomic() so they all succeed or roll back together. ATOMIC_REQUESTS wraps each view in a transaction.

Q27. What does select_for_update() do?

It locks the selected rows until the transaction ends, which prevents race conditions in cases like stock or balance updates. It must be used inside atomic().

Q28. What does transaction.on_commit() do?

It delays a callback until the transaction commits. This prevents problems such as a Celery task running before the data it needs has been saved.

Q29. What are Django signals?

Signals such as post_save let code react to events elsewhere. They decouple code but make flow harder to follow, so a direct service call is often clearer.

Q30. What is a custom manager?

A manager is the model's query interface, such as objects. A custom manager or QuerySet method holds reusable query logic, such as Article.objects.published().

Authentication & Django REST Framework

Q31. Why set a custom user model at the start?

Setting AUTH_USER_MODEL to a custom model, often based on AbstractUser, makes later changes such as email login much easier. Switching after the first migrations is difficult.

Q32. How does Django store passwords?

It stores a salted hash, not the password, using PBKDF2 by default and supporting others like Argon2. set_password() handles hashing and check_password() handles verification.

Q33. What is the difference between authentication and authorization?

Authentication confirms who the user is. Authorization decides what the user may do, using permissions and groups, such as with has_perm() or @permission_required.

Q34. What is Django REST Framework?

DRF is a toolkit for building APIs on Django. It adds serializers, viewsets, routers, authentication, permissions, throttling, pagination and a browsable API.

Q35. What does a serializer do?

A serializer converts model instances to JSON-friendly data and validates incoming data. ModelSerializer creates its fields and basic create and update logic from a model.

Q36. What is the difference between APIView and a ViewSet?

APIView maps HTTP methods to handler methods directly. A ViewSet groups actions such as list and retrieve, and a router can generate the URLs for it.

Q37. How does DRF handle permissions?

Set permission_classes such as IsAuthenticated, or write a custom class. has_permission checks the request, and has_object_permission checks a specific object.

Q38. What authentication options does DRF support?

Session, token and basic authentication are built in. JWT is commonly added with the djangorestframework-simplejwt package, and several schemes can be enabled together.

Q39. How do you paginate and throttle in DRF?

Use PageNumberPagination, LimitOffsetPagination or CursorPagination, with cursor being good for large, changing lists. Throttle classes limit request rates by user or IP.

Q40. How do you avoid N+1 queries in serializers?

Nested serializers can trigger a query per row. Add select_related and prefetch_related to the view's queryset, and measure the query count in tests.

Security, Performance & Deployment

Q41. How does Django protect against CSRF?

CsrfViewMiddleware checks a token on unsafe requests, and forms include it with {% csrf_token %}. Avoid csrf_exempt unless you have another protection in place.

Q42. How does Django protect against XSS?

Templates escape variables by default. Be careful with mark_safe, the safe filter and any user-supplied content displayed outside normal template escaping.

Q43. What settings must you change for production?

Set DEBUG = False, configure ALLOWED_HOSTS, load SECRET_KEY from the environment, and turn on secure cookies and HTTPS settings. Run python manage.py check --deploy to review them.

Q44. What is the difference between WSGI and ASGI in Django?

WSGI serves synchronous request-response apps through servers like Gunicorn. ASGI also supports async views and long-lived connections through servers like Uvicorn or Daphne.

Q45. Does Django support async?

Yes. Django supports async views, middleware and many async ORM methods like aget(). Some parts still run synchronously, and sync_to_async bridges blocking code.

Q46. What caching does Django offer?

Its cache framework supports per-view, template fragment and low-level caching, with backends including Redis and Memcached. Plan how to invalidate cached data when it changes.

Q47. How do you limit the columns loaded by a query?

only() and defer() load selected model fields, while values() and values_list() return plain data. They help with wide tables, but accessing deferred fields triggers more queries.

Q48. How do you run background tasks?

Celery with Redis or RabbitMQ is the common choice for long-running and scheduled work. Start tasks from transaction.on_commit() when they depend on newly saved data.

Q49. How do you test Django applications?

TestCase wraps each test in a transaction, and Client or DRF's APIClient send fake requests. assertNumQueries helps prevent query count regressions.

Q50. How is Django typically deployed?

Run Gunicorn or Uvicorn behind Nginx or a cloud load balancer, with PostgreSQL and Redis. Serve static files through a CDN or WhiteNoise, and run migrations as a controlled release step.