Django is the most battle-tested Python web framework and powers a significant share of Indian product companies' backends. Whether you are building a startup MVP or maintaining a production system serving millions of users, Django's batteries-included approach covers authentication, ORM, admin panel, and REST API support. This guide covers Django interview questions for Indian companies in 2026.
Django MTV architecture and request lifecycle
Django fundamentals:
1. MTV pattern: Django uses the MTV (Model-Template-View) pattern (equivalent to MVC: Model-View-Controller): - Model: defines the data structure (Python class that maps to a database table) - Template: HTML file with Django template language for rendering (not used in REST API backends; replaced by JSON serializers) - View: Python function or class that handles a request and returns a response
- Request lifecycle in Django:
- Browser sends HTTP request to the server
- Django's URL router (urls.py) matches the URL to a view function or class
- Middleware processes the request (authentication, CSRF check, logging)
- The view function/class executes: queries the database via the ORM, applies business logic
- The view returns an HttpResponse (HTML via Template, or JSON for API responses)
- Middleware processes the response
- Django sends the HTTP response to the browser
3. urls.py (URL routing): Django uses a URL configuration file that maps URL patterns to view functions. Include URLs from other apps using include(). URL patterns can capture parameters: path('posts/<int:pk>/', views.post_detail)
4. settings.py: Django's central configuration file. Key settings: DATABASES (database connection), INSTALLEDAPPS (all apps in the project), MIDDLEWARE (processing pipeline), STATICURL, MEDIAURL, SECRETKEY (keep in environment variable, never hardcode), DEBUG (set to False in production), ALLOWED_HOSTS (whitelist of valid hostnames).
Django ORM: models, queries, and relationships
Django ORM interview questions:
1. Django models: Each model class is a Python class that inherits from django.db.models.Model. Each field on the class maps to a column in the database table. Django automatically creates the database table when you run makemigrations and migrate.
2. Common field types: CharField (text up to max_length), TextField (unlimited text), IntegerField, DecimalField, BooleanField, DateField, DateTimeField, ForeignKey (many-to-one), ManyToManyField, OneToOneField.
3. ORM queries: Post.objects.all(): all posts. Post.objects.filter(author=user): filter by field. Post.objects.get(pk=1): get a single object (raises DoesNotExist if not found). Post.objects.exclude(isdraft=True): exclude. Post.objects.orderby('-created_at'): order (descending with -). Post.objects.first(): first result.
4. Avoiding N+1 queries: N+1 is the most important performance topic in Django ORM. The problem: fetching 100 posts then accessing post.author for each triggers 1 + 100 = 101 queries. Solution: - selectrelated(): for ForeignKey and OneToOneField relationships (SQL JOIN): Post.objects.selectrelated('author').all() fetches posts and authors in a single SQL query - prefetchrelated(): for ManyToMany and reverse ForeignKey relationships (separate query + Python-side joining): Post.objects.prefetchrelated('tags').all() fetches posts in one query and tags in one query, then joins in Python
5. Migrations: Django migrations are Python files that describe changes to the database schema. python manage.py makemigrations: auto-generates migration files from model changes. python manage.py migrate: applies pending migrations to the database. Never delete or edit migrations that have already been applied to a production database.
Django REST Framework: serializers, viewsets, and authentication
Django REST Framework (DRF) interview questions:
1. What is DRF? Django REST Framework is the most popular library for building REST APIs with Django. It adds serializers (data validation and transformation), class-based views for APIs (APIView, ViewSet), automatic browsable API, and authentication/permission classes.
2. Serializers: Serializers convert Django model instances to JSON and validate incoming JSON data for writes. ModelSerializer auto-generates fields from the model: ```python class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'title', 'body', 'author', 'createdat'] readonlyfields = ['id', 'author', 'createdat'] ```
3. ViewSets and Routers: ViewSet: a class that combines multiple views for a resource (list, detail, create, update, destroy) in one class. ModelViewSet: auto-implements all 5 standard actions. Router: automatically generates URL patterns for a ViewSet. This reduces boilerplate significantly: ```python router = DefaultRouter() router.register(r'posts', PostViewSet) urlpatterns = [path('api/', include(router.urls))] ```
4. Authentication in DRF: - SessionAuthentication: for browser-based clients; uses Django's session framework - TokenAuthentication: static API token (DRF's built-in; simple but tokens never expire) - JWT (djangorestframework-simplejwt): JSON Web Tokens; short-lived access tokens + long-lived refresh tokens; stateless; preferred for mobile API backends - Permission classes: IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly (allow GET but require auth for writes), custom permissions
5. Pagination in DRF: DRF has built-in pagination classes: PageNumberPagination, LimitOffsetPagination, CursorPagination. Configure globally in settings.py or per-view. Always paginate list endpoints to prevent returning unbounded datasets.
Practise Django and Python developer interview questions with HireStepX's AI voice interviewer. Get scored feedback on your explanations of ORM queries, REST API design, and middleware. First 2 sessions free.
Practice freeDjango middleware, signals, and Celery
Django advanced topics:
1. Django middleware: Middleware is a hook into Django's request/response processing. Each middleware is a class with processrequest() and processresponse() methods (or a callable that wraps the view). Common uses: logging request times, adding CORS headers, custom authentication, request decompression.
2. Django signals: Signals allow decoupled components to receive notifications when certain events occur. Built-in signals: presave, postsave (sent before/after a model is saved), predelete, postdelete, requeststarted, requestfinished. Use signals to: send welcome emails when a new user registers (post_save on User), update a search index when a post is saved, invalidate a cache when data changes. Django signals vs Celery tasks: signals are synchronous (run in the same request); Celery tasks are asynchronous (run in a background worker). For time-consuming operations (sending emails, processing images), send a Celery task from the signal handler rather than doing the work in the signal directly.
3. Celery for background tasks: Celery is the most popular task queue for Django applications. Define a task with the @sharedtask decorator; call it asynchronously with .delay() or .applyasync(). Celery uses a message broker (Redis is most common for Indian startups; RabbitMQ is the alternative). Celery Beat: a built-in scheduler that triggers tasks on a schedule (cron-like; e.g., run a nightly report every day at 2am IST).
Frequently asked questions
Explore more