Ace Your Interviews 🎯

Browse our collection of interview questions across various technologies.

DjangoBeginner

What is Django and what problem does it solve?

Answer

Django is a high-level Python web framework that solves the problem of building complete, secure, database-backed web applications quickly. It follows the 'batteries included' philosophy — providing an ORM, admin panel, authentication system, form validation, template engine, and URL routing out of the box. This lets small teams ship production-ready applications without building foundational infrastructure from scratch.

DjangoBeginner

Explain Django's MVT architecture.

Answer

Model: Python classes that define the database structure and business rules — Django's ORM converts them to SQL tables. View: Python functions or classes that receive HTTP requests, use Models to query data, and return HTTP responses. Template: HTML files with Django template language tags ({% %}) and variables ({{ }}) that render dynamic HTML. Unlike MVC, Django's 'Controller' is the URL dispatcher itself — it routes requests to the correct view.

DjangoBeginner

What is the Django ORM and why use it instead of raw SQL?

Answer

The ORM (Object-Relational Mapper) lets you interact with the database using Python code instead of SQL strings. Product.objects.filter(price__lte=50000) generates SELECT * FROM products WHERE price <= 50000 automatically. Benefits: database-agnostic code (same Python works with PostgreSQL, MySQL, SQLite), automatic SQL injection prevention via parameterized queries, Python objects instead of raw tuples, and migration tracking. Raw SQL is still possible with raw() or cursor.execute() when needed.

DjangoBeginner

What is a Django migration and why is it important?

Answer

A migration is a Python file that describes a change to the database schema — adding a table, adding a column, changing a field type. makemigrations creates the migration file from your model changes. migrate applies it to the database. Migrations are version control for your database schema — they track every change, allow rollbacks, and ensure all developers and all environments have the same database structure.

DjangoBeginner

What is the difference between a FunctionBasedView and a ClassBasedView?

Answer

FBVs are Python functions: def product_list(request): ... — explicit, readable, and flexible. CBVs are Python classes: class ProductListView(ListView): ... — more reusable, leverage inheritance and mixins, and Django's generic CBVs (ListView, DetailView, CreateView) provide complete CRUD functionality with less code. Use FBVs for complex custom logic; use CBVs for standard CRUD that fits generic patterns.

DjangoBeginner

What is Django's admin panel and how do you register a model with it?

Answer

Django admin is an auto-generated CRUD interface for your database models, accessible at /admin/. Register models with @admin.register(Product) decorator on a ModelAdmin class, or admin.site.register(Product). Customize with list_display (visible columns), list_filter (sidebar filters), search_fields (search bar), and prepopulated_fields (auto-fill slug from name).

DjangoBeginner

What is CSRF and how does Django protect against it?

Answer

Cross-Site Request Forgery — an attacker tricks a logged-in user's browser into sending a malicious POST request to your site using the user's active session. Django prevents it with CsrfViewMiddleware (enabled by default) — every HTML form must include {% csrf_token %} which embeds a hidden token. Django validates this token on every POST request, rejecting requests without a valid token.

DjangoBeginner

What is the difference between CharField and TextField in Django models?

Answer

CharField requires a max_length parameter and maps to VARCHAR in SQL — use for short strings: names, titles, emails, phone numbers. TextField has no max_length and maps to TEXT — use for long content: blog post body, product description, user bio. In Django admin, CharField renders as a single-line input; TextField renders as a multi-line textarea.

DjangoBeginner

How does Django handle static files and media files?

Answer

Static files are CSS, JavaScript, and images bundled with your project code. Configured via STATICFILES_DIRS and STATIC_URL. Run collectstatic to gather all static files for production serving. Media files are user uploads (ImageField, FileField). Configured via MEDIA_ROOT and MEDIA_URL. In development, add url patterns to serve them. In production, serve via Nginx or cloud storage (S3/Cloudinary).

DjangoBeginner

What is Django's request/response cycle?

Answer

HTTP request arrives → WSGI server (Gunicorn) passes to Django → middleware stack processes request top-to-bottom (security, session, auth, CSRF) → URL dispatcher matches pattern → view function/class executes with ORM queries → template renders HTML (or DRF serializer returns JSON) → middleware processes response bottom-to-top → HTTP response returned to client.

DjangoIntermediate

Explain the N+1 query problem and how to fix it with Django ORM.

Answer

N+1 occurs when you fetch N objects and then access a FK attribute inside a loop — generating 1 initial query + N additional queries. for p in Product.objects.all(): p.seller.email executes 1 + N queries. Fix with select_related('seller') for ForeignKey (single JOIN query) and prefetch_related('tags') for ManyToMany or reverse FK (2 queries total). Use Django Debug Toolbar to detect N+1 in development.

DjangoIntermediate

What is Django REST Framework and what are its core components?

Answer

DRF is a toolkit for building REST APIs with Django. Core components: Serializers (validate and convert model instances to/from JSON), ViewSets (class-based views for CRUD API endpoints), Routers (auto-generate URL patterns for viewsets), Authentication backends (JWT, Token, Session), Permissions (IsAuthenticated, IsOwnerOrReadOnly), Throttling (rate limiting), Pagination (PageNumberPagination), and Filtering (django-filter integration).

DjangoIntermediate

What is a Django serializer and how does it differ from a Django form?

Answer

Both validate data and convert between Python objects and other formats. Forms: validate POST data from HTML forms, render HTML input widgets, save to models. Serializers: validate JSON data from API requests, convert model instances to JSON for API responses, used with DRF. Serializers also handle nested data (related model serialization) and explicit read_only/write_only field configuration that forms don't need.

DjangoIntermediate

How do you implement custom permissions in Django REST Framework?

Answer

Create a class inheriting permissions.BasePermission and implement has_permission(self, request, view) for view-level checks and has_object_permission(self, request, view, obj) for object-level checks. Return True to allow, False to deny. Example: IsOwnerOrReadOnly returns True for GET requests (read-only), returns True for write methods only if obj.owner == request.user. Apply with permission_classes = [IsAuthenticated, IsOwnerOrReadOnly] on a ViewSet.

DjangoIntermediate

What is Django's signal system? Give a real-world example.

Answer

Signals are a publish/subscribe mechanism — code can send a signal when something happens, and registered receivers respond. Built-in signals: post_save (after a model is saved), pre_save (before save), post_delete. Example: @receiver(post_save, sender=Order) def send_confirmation_email(sender, instance, created, **kwargs): if created: send_order_confirmation_email.delay(instance.pk). Signals decouple the Order model from email-sending logic.

DjangoIntermediate

How do Q objects and F expressions work in Django ORM?

Answer

Q objects enable complex filter logic: Product.objects.filter(Q(name__icontains='laptop') | Q(description__icontains='laptop')). Q supports AND (&), OR (|), and NOT (~). F expressions reference a database column in queries without fetching the value to Python: Product.objects.filter(stock__lt=F('min_stock_alert')) compares two columns in SQL. F() is also used for atomic updates: Product.objects.filter(pk=id).update(stock=F('stock') - 1) prevents race conditions.

DjangoIntermediate

Explain Django's authentication system — how does login/logout work?

Answer

Authentication uses sessions: django.contrib.auth.authenticate() verifies credentials, django.contrib.auth.login(request, user) creates a session and sets SESSION_COOKIE on the response. On subsequent requests, Django's SessionMiddleware loads the session and AuthenticationMiddleware sets request.user. logout(request) flushes the session. AbstractUser lets you extend the User model. For APIs, JWT replaces session cookies — simplejwt issues signed tokens that clients send in the Authorization header.

DjangoIntermediate

What is select_related vs prefetch_related and when do you use each?

Answer

select_related uses SQL JOIN — fetches the related object in the same query. Use for ForeignKey and OneToOne relationships (single object per row): Product.objects.select_related('category', 'seller'). prefetch_related uses a second SQL query — fetches all related objects and joins them in Python. Use for ManyToMany, reverse ForeignKey, and GenericRelation: Product.objects.prefetch_related('tags', 'reviews'). Rule: ForeignKey → select_related; ManyToMany/reverse FK → prefetch_related.

DjangoIntermediate

How do you write tests for a Django REST Framework API?

Answer

Use APIClient from rest_framework.test: client = APIClient(). Authenticate with client.force_authenticate(user=user) (for unit tests) or client.post('/api/auth/login/', ...) for integration tests. Call client.get('/api/products/'), client.post('/api/products/', data, format='json'). Assert response.status_code, response.data shape and values. Use TestCase.setUp() with factory_boy to create test data. Run with pytest-django for better output and fixture management.

DjangoIntermediate

What is Celery and how does it integrate with Django?

Answer

Celery is a distributed task queue. Workers (separate processes) pick up tasks from a message broker (Redis/RabbitMQ) and execute them asynchronously. Integration: create celery.py in project root, configure CELERY_BROKER_URL in settings.py, decorate functions with @shared_task, call task.delay() from views. Celery Beat handles periodic tasks. Use .delay() for fire-and-forget, .apply_async() for delayed or scheduled execution, .get() (with caution) to wait for results.

DjangoIntermediate

How do migrations work internally in Django? What happens during migrate?

Answer

Each migration file has dependencies (what previous migration it builds on), operations (AddField, CreateModel, RunSQL, etc.), and is Python code that describes schema changes. migrate reads the django_migrations table to find which migrations have been applied, then applies unapplied ones in dependency order. Each operation calls the database backend's schema editor to generate and execute the correct SQL (CREATE TABLE, ALTER TABLE, etc.). Forward migrations run upgrade(); rollback runs downgrade() with the --fake flag.

DjangoAdvanced

How would you scale a Django application from 1,000 to 1 million users?

Answer

Horizontal scaling: multiple Gunicorn workers behind Nginx load balancer, auto-scaled via Docker/Kubernetes. Database: PostgreSQL read replicas for read-heavy queries, PgBouncer for connection pooling. Caching: Redis for database query caching, per-view caching, session storage. CDN: CloudFront/Cloudflare for static/media files. Celery: move background work to separate worker fleet. Async: Django Channels for WebSockets. Database: add indexes on all filter/order fields, optimize slow queries with EXPLAIN ANALYZE. Search: Elasticsearch for product catalog search.

DjangoAdvanced

Explain Django Channels and how it enables real-time features.

Answer

Django Channels extends Django to handle WebSockets, long polling, and background tasks via an ASGI interface. The channel layer (backed by Redis) routes messages between consumers (WebSocket handler classes, similar to Django views). A WebSocketConsumer defines connect(), disconnect(), and receive() methods. Real-time patterns: broadcast (all connected clients receive event), room-based routing (per-chat-room channel groups), user-specific channels (notify specific user). Use django-channels with Daphne (ASGI server) instead of Gunicorn (WSGI).

DjangoAdvanced

How do you implement multi-tenancy in Django?

Answer

Schema isolation: django-tenants creates a separate PostgreSQL schema per tenant — complete data isolation, no cross-tenant leakage, slightly complex routing. Row-level isolation: every model has an organization ForeignKey; a custom middleware sets the tenant from the request domain; a custom manager filters all queries by organization. Schema isolation is more secure and simpler for large enterprises; row-level is simpler to implement for most SaaS products.

DjangoAdvanced

How do you handle database migrations for a large production table with millions of rows?

Answer

Adding a non-nullable column: first add as nullable (no table lock), backfill with a management command or Celery batch task, then add NOT NULL constraint with a short lock. Adding an index: use CREATE INDEX CONCURRENTLY (PostgreSQL) via RunSQL migration — doesn't lock the table. Renaming a column: add new column, dual-write both old and new, migrate reads, drop old column across three deployments. Always run migrations on a production data copy first. Consider django-postgres-extra for safe migrations.

DjangoAdvanced

What is the Django content types framework and what is it used for?

Answer

django.contrib.contenttypes provides a GenericForeignKey — a FK that can point to any model. Use cases: a Comment model that can attach to any content type (Article, Product, Video) without separate comment tables per model; a Like model reused across content types; audit log entries pointing to any changed object; notification system where any event type produces a notification. Access: ContentType.objects.get_for_model(Product) returns the ContentType instance for Product.

DjangoAdvanced

How do you implement a custom Django authentication backend?

Answer

Create a class with authenticate(request, **credentials) method and optionally get_user(user_id). authenticate() returns a user or None. Example: EmailBackend that allows login with email instead of username — queries User.objects.get(email=username). Register in settings: AUTHENTICATION_BACKENDS = ['accounts.backends.EmailBackend', 'django.contrib.auth.backends.ModelBackend']. Django tries backends in order, uses the first that returns a user.

DjangoAdvanced

What is Django's cache framework? Explain the different cache backends and when to use each.

Answer

Django cache framework provides a unified API (cache.get, cache.set, cache.delete) over multiple backends. Memcached: fast, simple, no persistence — use for pure caching (session data, query results) where loss on restart is acceptable. Redis: fast, persistent, supports expiry, pub/sub, sorted sets — use for caching + Celery broker + Django Channels channel layer (one service). Database: slow, no added value — only for platforms without Redis/Memcached. Filesystem: for development only. Dummy: for testing (all operations are no-ops).

DjangoAdvanced

How would you debug a slow Django API endpoint?

Answer

1) Django Debug Toolbar in development — shows query count, query time, and SQL per request. 2) Log slow queries: set LOGGING config to log queries over 100ms. 3) Add query analysis: .explain() on the queryset. 4) EXPLAIN ANALYZE in PostgreSQL directly for the generated SQL. 5) Check for missing indexes on filter/order fields. 6) Check for N+1 queries — add select_related/prefetch_related. 7) Check for non-indexed full-table scans. 8) In production, use Sentry performance monitoring and py-spy sampling profiler.

DjangoAdvanced

Explain Django's middleware system and write a custom middleware.

Answer

Middleware is a hook into Django's request/response processing. Each middleware can process the request before it reaches the view (__call__ or process_request), and the response after the view returns (process_response). MIDDLEWARE is a list — order matters. Example custom middleware: class RequestLoggingMiddleware: def __init__(self, get_response): self.get_response = get_response; def __call__(self, request): import time; start = time.time(); response = self.get_response(request); duration = time.time() - start; logger.info(f'{request.method} {request.path} {response.status_code} {duration:.3f}s'); return response.

DjangoAdvanced

How do you implement full-text search in Django?

Answer

PostgreSQL full-text search via django.contrib.postgres.search: SearchVector to index fields, SearchQuery for the query, SearchRank for relevance ordering. Product.objects.annotate(rank=SearchRank(SearchVector('name', 'description'), SearchQuery(q))).filter(rank__gte=0.1).order_by('-rank'). Add SearchVectorField with a trigger or signal for pre-computed search vectors on large tables. For more advanced needs: Elasticsearch with django-elasticsearch-dsl — full-text, faceted search, autocomplete, and analytics across any scale.

DjangoAdvanced

What are Django's database transactions and when do you need them?

Answer

Transactions ensure a set of database operations all succeed or all roll back atomically. Use cases: place_order() must atomically create the Order AND reduce inventory — if either fails, both revert. Django wraps each request in a transaction by default (ATOMIC_REQUESTS=True) or use @transaction.atomic decorator on specific functions. For long transactions, use transaction.atomic() context manager. Celery tasks should NOT run inside database transactions — database connections are not shared across processes.

Ready for a real challenge?

Master Django