PrepStack › Backend › Django & DRF

Django & DRF interview cheat sheet

MTV, ORM & querysets, migrations, middleware, signals, auth, Django REST Framework

Django interviews check that you understand what happens between the HTTP request and the SQL query: the request lifecycle, the ORM and its laziness, N+1 problems, transactions, middleware and security defaults. Backend roles then move to Django REST Framework: serializers, viewsets, permissions, throttling and pagination. Read the 15-minute revision first, then switch to Quiz mode and answer out loud. Current versions: Django 5.2 is the LTS, Django 6.0 (Dec 2025) needs Python 3.12+.

15-minute revision

  1. Django is MTV: Model (data + ORM), Template (presentation), View (request → response logic). The framework itself plays the MVC 'controller' through its URL dispatcher.
  2. A project is the deployable site (settings, root URLconf, WSGI/ASGI entry). An app is a reusable feature package listed in INSTALLED_APPS.
  3. Request path: server → WSGI/ASGI handler → middleware (top to bottom) → URL resolver → view → middleware (bottom to top) → response.
  4. QuerySets are lazy: chaining filter() builds SQL but runs nothing. They hit the DB on iteration, list(), len(), bool(), step slicing or repr(), then cache the result.
  5. Q objects build OR / NOT conditions. F objects refer to a column in the DB, so update(stock=F('stock') - 1) is atomic and race-free.
  6. aggregate() returns one dict for the whole queryset. annotate() adds a value per row (GROUP BY). Filtering after annotate becomes HAVING.
  7. N+1: one query for the list plus one per row for a relation. Fix with select_related (FK / one-to-one, SQL JOIN) or prefetch_related (M2M / reverse FK, second query + Python join).
  8. queryset.update(), bulk_create() and bulk_update() skip save() and the save signals. Remember this before relying on signals.
  9. transaction.atomic() wraps work in a transaction; nested blocks become savepoints. Use transaction.on_commit() to send emails or Celery tasks only after commit.
  10. null=True is about the database column. blank=True is about form validation. For strings, prefer blank=True with an empty string instead of NULL.
  11. Create migrations with makemigrations, apply them with migrate, inspect with sqlmigrate. Data migrations use RunPython with apps.get_model(), never a direct import.
  12. Define a custom user model (AbstractUser) at the start of every project and point AUTH_USER_MODEL at it. Changing it later is painful.
  13. CSRF protection is on by default for unsafe methods. The template output is auto-escaped against XSS. The ORM parameterises queries against SQL injection.
  14. Signals run synchronously inside the same transaction. Prefer an explicit service function or overriding save() when the logic belongs to your own models.
  15. DRF: Serializer = validation + conversion, ModelSerializer generates fields from the model. ModelViewSet + DefaultRouter gives full CRUD URLs in a few lines.
  16. Production: DEBUG=False, ALLOWED_HOSTS, secret from env, collectstatic, Gunicorn (WSGI) or Uvicorn (ASGI) behind Nginx, and manage.py check --deploy.

Architecture & request handling

MTV, project vs app & the request lifecycle

Django splits code into Models, Templates and Views, and routes every request through middleware, the URL resolver and a view.

  • Model: a Python class mapped to a table. Template: HTML with the Django Template Language. View: a callable that takes an HttpRequest and returns an HttpResponse.
  • MTV is Django's name for MVC. The Django view is closer to an MVC controller, and the template is the MVC view.
  • django-admin startproject site creates manage.py, settings.py, the root urls.py, wsgi.py and asgi.py.
  • python manage.py startapp blog creates an app: models.py, views.py, admin.py, apps.py, tests.py and a migrations/ package. Add it to INSTALLED_APPS.
  • Each app has an AppConfig class. Its ready() method is the place to connect signals or do start-up work.
  • manage.py is django-admin with DJANGO_SETTINGS_MODULE already set for your project.

Interview questions

  • What is MTV and how does it map to MVC?
  • What is the difference between a project and an app?
  • Walk me through what happens when a request hits a Django site.
  • Where should you connect signals or run start-up code?

Settings & URLconf

settings.py is plain Python configuration; urls.py maps URL patterns to views with path() and include().

  • DJANGO_SETTINGS_MODULE decides which settings module loads. Read values through from django.conf import settings, never by importing your settings file.
  • Key settings: DEBUG, SECRET_KEY, ALLOWED_HOSTS, INSTALLED_APPS, MIDDLEWARE, DATABASES, TEMPLATES, STATIC_ROOT, AUTH_USER_MODEL, DEFAULT_AUTO_FIELD.
  • Split settings per environment (base / dev / prod modules) or read them from environment variables. Never commit secrets.
  • path('posts/<int:pk>/', view, name='post-detail') uses converters: str, int, slug, uuid, path. Use re_path() for regex patterns.
  • include('blog.urls') mounts an app's URLconf under a prefix. Set app_name = 'blog' there to namespace names: reverse('blog:post-detail', args=[1]).
  • Patterns are tried in order; the first match wins. Name every URL and use reverse() in Python and {% url %} in templates instead of hard-coding paths.

Interview questions

  • How do you manage settings for dev, staging and production?
  • Why use reverse() and URL names instead of hard-coded paths?

Views: FBV vs CBV & generic views

A view is any callable that takes a request and returns a response; class-based views add reuse through inheritance and mixins.

  • Function-based views (FBV) are explicit and easy to read. You branch on request.method yourself.
  • Class-based views (CBV) dispatch by HTTP method (get(), post()), and as_view() creates a new instance per request, so storing state on self is safe.
  • Generic views cover common patterns: TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView, FormView, RedirectView.
  • Customise generic views by overriding hooks: get_queryset(), get_context_data(), get_object(), form_valid(), get_success_url().
  • Add behaviour with mixins such as LoginRequiredMixin and PermissionRequiredMixin. They must come before the base view in the class list.
  • Shortcuts: render(), redirect(), get_object_or_404(), get_list_or_404(). Return JsonResponse for simple JSON.

Interview questions

  • When would you choose an FBV over a CBV?
  • How does as_view() work?
  • How do you restrict an UpdateView so users can only edit their own objects?

Models, migrations & the ORM

Models, fields & Meta

A model class maps to a table; fields map to columns, and Meta holds table-level options like ordering, constraints and indexes.

  • Common fields: CharField(max_length), TextField, IntegerField, DecimalField(max_digits, decimal_places), BooleanField, DateTimeField(auto_now_add / auto_now), EmailField, SlugField, JSONField, FileField / ImageField, UUIDField.
  • Relations: ForeignKey (many-to-one), OneToOneField, ManyToManyField (with an optional through model for extra columns).
  • on_delete is required on FKs: CASCADE, PROTECT, RESTRICT, SET_NULL (needs null=True), SET_DEFAULT, SET(...), DO_NOTHING.
  • related_name names the reverse accessor (author.books.all() instead of author.book_set.all()).
  • Meta options: ordering, db_table, verbose_name, constraints (UniqueConstraint, CheckConstraint), indexes, abstract, proxy, permissions.
  • Every model gets an auto primary key. New projects set DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'. Django 5.2 added CompositePrimaryKey.

Interview questions

  • What is the difference between null=True and blank=True?
  • Explain the on_delete options.
  • Abstract base class vs multi-table inheritance vs proxy model?

Migrations

Migrations are versioned Python files that describe schema changes; makemigrations writes them and migrate applies them.

  • makemigrations compares models to the state built from existing migration files (not the live DB) and writes new operations.
  • migrate applies unapplied migrations and records them in the django_migrations table. migrate app 0003 rolls back to that migration.
  • Inspect with showmigrations and sqlmigrate app 0004 (prints the SQL). --fake marks a migration applied without running it.
  • Data migrations use RunPython(forwards, backwards). Get models with apps.get_model('shop', 'Book'), the historical version, not by importing.
  • Two developers creating migration 0005 on different branches causes a conflict. makemigrations --merge creates a merge migration.
  • squashmigrations combines a long chain into one file to speed up test DB creation.

Interview questions

  • What is the difference between makemigrations and migrate?
  • Why must data migrations use apps.get_model()?
  • How do you deploy a schema change with zero downtime?
  • Two branches both added migration 0007. What do you do?

QuerySets: laziness, Q & F, managers

A QuerySet is a lazy, chainable description of a SELECT; Q combines conditions, F references columns, and managers are where querysets start.

  • Chaining filter(), exclude(), order_by(), values() returns a new QuerySet and runs no SQL.
  • Evaluation happens on iteration, list(), len(), bool(), repr(), pickling or slicing with a step. The rows are then kept in the result cache.
  • Cheap checks: exists() instead of if qs:, count() instead of len(qs) when you do not need the rows. A slice like qs[:10] becomes LIMIT and stays lazy.
  • get() raises DoesNotExist or MultipleObjectsReturned. first() returns None. get_or_create() and update_or_create() return (obj, created).
  • Keyword lookups are ANDed. Use Q for | (OR), & and ~ (NOT). Use F to compare two columns or update a column from its own value in SQL.
  • A manager (objects) is the entry point. Put reusable filters on a custom QuerySet and expose it with QuerySet.as_manager() so they chain.
  • Use iterator() for huge result sets (no cache, streams in chunks) and values() / values_list(flat=True) when you do not need model instances.

Interview questions

  • What does it mean that QuerySets are lazy?
  • What are Q and F objects?
  • count() vs len(), and exists() vs if qs?
  • What is a manager and why write a custom one?

annotate vs aggregate, subqueries

aggregate() collapses the queryset into one dict; annotate() adds a computed value to every row using GROUP BY.

  • Book.objects.aggregate(total=Sum('price')) → {'total': ...}. It is terminal: it returns a dict, not a queryset.
  • Author.objects.annotate(n=Count('books')) → every author gets an n attribute. You can then filter(n__gte=2) (SQL HAVING) or order_by('-n').
  • Order matters: filter() before annotate() limits which related rows are counted (WHERE); filter() on the annotation after it becomes HAVING.
  • Annotating two multi-valued relations at once (Count('books'), Count('reviews')) multiplies rows through the joins. Use distinct=True or subqueries.
  • Subquery + OuterRef embed a correlated subquery; Exists() is ideal for 'has any' checks. Use Coalesce to turn NULL into a default.
  • values('field').annotate(...) groups by that field, like GROUP BY field.

Interview questions

  • Difference between aggregate() and annotate()?
  • Why does Count('books') give a wrong, too-large number when I also count reviews?
  • How would you list authors whose newest book is cheaper than 20?

N+1, select_related, prefetch_related, only/defer

Accessing a relation inside a loop runs one query per row; select_related and prefetch_related load the relations up front.

  • N+1: for b in Book.objects.all(): b.author.name runs 1 query for books plus N queries for authors.
  • select_related('author'): forward FK and one-to-one (both directions). One query with a SQL JOIN. Can follow chains: 'author__publisher'.
  • prefetch_related('tags'): M2M and reverse FK (and also works for FKs). Runs one extra query per relation with WHERE id IN (...) and joins in Python.
  • Use Prefetch('books', queryset=Book.objects.filter(published=True), to_attr='published_books') to filter or order the prefetched rows.
  • Calling .filter() on a prefetched relation (author.books.filter(...)) ignores the cache and queries again. Filter in the Prefetch instead.
  • only() / defer() limit loaded columns. Touching a deferred field later runs one query per object: a new N+1.
  • Detect it with Django Debug Toolbar, assertNumQueries in tests, or nplusone / django-silk in development.

Interview questions

  • What is the N+1 query problem and how do you fix it in Django?
  • Difference between select_related and prefetch_related?
  • When can only() make performance worse?
  • Your API endpoint makes 300 queries. How do you investigate?

Bulk operations, transactions & locking

Bulk APIs cut round trips but skip save() and signals; transaction.atomic gives all-or-nothing writes, and select_for_update locks rows.

  • bulk_create(objs, batch_size=1000) inserts many rows in few queries. It does not call save() or send pre_save/post_save. Options: ignore_conflicts, update_conflicts.
  • bulk_update(objs, ['price']) and queryset.update(...) run UPDATE statements with no save() and no signals. auto_now fields are not touched by update().
  • queryset.delete() deletes in SQL but still emulates cascades and sends pre_delete / post_delete per object.
  • By default Django runs in autocommit mode: each query commits on its own. ATOMIC_REQUESTS = True wraps every view in a transaction.
  • transaction.atomic() (decorator or with) commits on success and rolls back on exception. Nested atomic blocks create savepoints.
  • select_for_update() takes row locks (SELECT ... FOR UPDATE) until the transaction ends. It must run inside atomic. Options: nowait, skip_locked, of.
  • transaction.on_commit(fn) runs fn only after the outer transaction commits. Use it for emails, cache invalidation and Celery tasks.

Interview questions

  • Why might bulk_create or update() break your app's logic?
  • How does transaction.atomic behave when nested?
  • Two users buy the last item at the same time. How do you prevent overselling?
  • What is transaction.on_commit for?

Request pipeline, templates & auth

Middleware

Middleware is a chain of callables wrapped around the view that can change the request, the response, or short-circuit both.

  • A middleware is a factory that receives get_response and returns a callable taking a request. Code before get_response(request) runs on the way in, code after it runs on the way out.
  • Order in MIDDLEWARE matters: top runs first on the request and last on the response.
  • Optional hooks on class-based middleware: process_view() (after URL resolution, before the view), process_exception(), process_template_response().
  • Typical order: SecurityMiddleware, SessionMiddleware, CommonMiddleware, CsrfViewMiddleware, AuthenticationMiddleware, MessageMiddleware, XFrameOptionsMiddleware.
  • AuthenticationMiddleware needs the session, so it must come after SessionMiddleware. It sets request.user lazily.
  • Good uses: request IDs, timing, tenant detection, headers. Bad uses: per-view business logic (use decorators or mixins).

Interview questions

  • What is middleware in Django and how is the order applied?
  • Middleware vs decorator vs signal: when do you use each?
  • What does process_view give you that __call__ does not?

Signals (and when not to use them)

Signals let decoupled code react to events like post_save, but they are synchronous, hidden and easy to bypass.

  • Model signals: pre_save, post_save (with created), pre_delete, post_delete, m2m_changed. Others: request_started, request_finished, post_migrate, user_logged_in.
  • Connect with @receiver(post_save, sender=Order) and import the module in AppConfig.ready(). Use dispatch_uid to avoid duplicate registration.
  • Receivers run synchronously, in the same thread and transaction as the sender. A slow or failing receiver slows or breaks the save.
  • They are not sent by queryset.update(), bulk_create(), bulk_update() or raw SQL.
  • Good use: reacting to models you do not own (e.g. creating a Profile when a third-party User is created), or library hooks.
  • Prefer explicit code for your own models: override save(), or call a service function like create_order() that does everything in sequence.

Interview questions

  • What are Django signals and how do they work?
  • Are signals asynchronous?
  • Why do many teams avoid signals for business logic?

Templates, forms & ModelForm

The Django Template Language renders auto-escaped HTML with inheritance; forms validate input and ModelForms map it onto models.

  • Template syntax: {{ variable|filter }}, {% tag %}. Inheritance with {% extends 'base.html' %} and {% block content %}. Reuse with {% include %}.
  • Output is auto-escaped. |safe and mark_safe() turn this off, so never apply them to user input.
  • Context processors add variables to every template (request, user, messages). Custom tags and filters live in templatetags/.
  • Django 6.0 added template partials: {% partialdef name %} and {% partial name %}, also loadable as 'page.html#name'.
  • A Form declares fields; is_valid() runs field cleaning, then clean_<field>() methods, then clean() for cross-field rules. Read data from cleaned_data.
  • A ModelForm builds fields from a model (Meta.model, Meta.fields), validates model constraints and saves with save(). save(commit=False) lets you set extra fields first.

Interview questions

  • Form vs ModelForm?
  • Explain the form validation order.
  • How does Django protect templates against XSS?

Auth, custom user, permissions & admin

django.contrib.auth gives users, groups, permissions and login views; always start with a custom user model, and use the admin for internal CRUD.

  • authenticate(request, username, password) checks credentials through AUTHENTICATION_BACKENDS; login() stores the user id in the session; logout() flushes it.
  • Passwords are hashed (PBKDF2 by default, Argon2 / bcrypt available). Use set_password(), never assign user.password directly.
  • Custom user: extend AbstractUser to add fields, or AbstractBaseUser + PermissionsMixin for full control (e.g. email login). Set AUTH_USER_MODEL before the first migration.
  • Reference the user with get_user_model() in code and settings.AUTH_USER_MODEL in FKs.
  • Each model gets add, change, delete, view permissions. Check with user.has_perm('shop.change_book'). Group users with Groups. Object-level permissions need a backend such as django-guardian.
  • Protect views with @login_required, @permission_required, LoginRequiredMixin, or (Django 5.1+) LoginRequiredMiddleware with @login_not_required on public views.
  • Admin: @admin.register(Model) with a ModelAdmin: list_display, list_filter, search_fields, list_select_related, autocomplete_fields, inlines, actions, readonly_fields.

Interview questions

  • Why should every new project use a custom user model?
  • AbstractUser vs AbstractBaseUser?
  • How do permissions work in Django?
  • How are passwords stored?

Sessions, CSRF & security settings

Django ships defences for CSRF, XSS, SQL injection, clickjacking and session fixation; you must still configure HTTPS settings for production.

  • Sessions: the cookie holds only a random session key; the data lives in the backend: database (default), cache, cached_db, file, or signed cookies.
  • Login rotates the session key (cycle_key) to stop session fixation. Session cookies are HttpOnly by default.
  • CSRF: CsrfViewMiddleware checks POST/PUT/PATCH/DELETE for a token (form field csrfmiddlewaretoken or X-CSRFToken header) matching the csrftoken cookie, and checks Origin for HTTPS requests.
  • Cross-origin front ends must be listed in CSRF_TRUSTED_ORIGINS. Use @csrf_exempt only for endpoints authenticated another way (e.g. signed webhooks).
  • Production settings: DEBUG=False, ALLOWED_HOSTS, SECURE_SSL_REDIRECT, SECURE_HSTS_SECONDS, SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE, SECURE_PROXY_SSL_HEADER behind a proxy.
  • SQL injection: the ORM parameterises everything. With raw() or cursor.execute(), pass values as params, never with f-strings.
  • Django 6.0 adds built-in Content Security Policy support (ContentSecurityPolicyMiddleware, SECURE_CSP). X_FRAME_OPTIONS = 'DENY' blocks clickjacking.

Interview questions

  • How does Django's CSRF protection work?
  • Where is session data stored?
  • Do you need CSRF protection for a JSON API?

Performance, async & background work

Caching, static & media files

Django caches at site, view, fragment or low-level granularity through pluggable backends; static files are collected and served by a web server or CDN.

  • Backends: RedisCache (built in since 4.0), PyMemcacheCache, LocMemCache (default, per process), DatabaseCache, FileBasedCache, DummyCache.
  • Levels: per-site (UpdateCacheMiddleware + FetchFromCacheMiddleware), per-view (@cache_page(60)), template fragment ({% cache 300 sidebar %}), low-level (cache.get/set/get_or_set/delete).
  • Invalidate explicitly on writes (delete keys in on_commit) or use versioned keys. TTL alone means stale data until expiry.
  • Static files (your CSS/JS): STATIC_URL, STATICFILES_DIRS, and STATIC_ROOT as the target of collectstatic. Use ManifestStaticFilesStorage for hashed names and long cache headers.
  • Media files (user uploads): MEDIA_URL, MEDIA_ROOT, FileField(upload_to=...). In production store them on S3/GCS with django-storages; never serve them from Django itself.
  • Since 4.2, storages are configured with the STORAGES setting (default and staticfiles keys).

Interview questions

  • What caching levels does Django offer?
  • Static files vs media files?
  • What does collectstatic do?

Async views, ASGI & Celery

Django supports async def views under ASGI and an async ORM interface, but heavy or slow work belongs in background workers such as Celery.

  • WSGI is the synchronous Python server interface; ASGI adds async, WebSockets and long-lived connections. Run ASGI with Uvicorn, Daphne or Hypercorn.
  • async def views work under both. Under WSGI each async view gets its own event loop, so you lose the benefit. Gains come from concurrent I/O (many outbound HTTP calls) under ASGI.
  • The ORM has async methods: aget(), acreate(), acount(), aexists(), async for obj in qs. Calling the sync ORM from async code raises SynchronousOnlyOperation.
  • Wrap sync code with sync_to_async() (runs in a thread) and async code with async_to_sync(). Transactions do not work in async mode yet; wrap them in a sync function.
  • Celery: a separate worker process consumes tasks from a broker (Redis or RabbitMQ). Define with @shared_task, call with .delay() or .apply_async(countdown=..., eta=...). celery beat schedules periodic tasks.
  • Pass ids, not model instances, to tasks. Make tasks idempotent, set retries with backoff, and enqueue with transaction.on_commit (Celery 5.4+ also has delay_on_commit()).
  • Django 6.0 ships a built-in Tasks framework (@task, .enqueue()), but it defines the API only; you still need a backend and a worker to run tasks.

Interview questions

  • WSGI vs ASGI?
  • Does making views async make Django faster?
  • Why pass an id instead of a model object to a Celery task?
  • A Celery task sometimes cannot find the order it was given. Why?
  • How do you make Celery tasks reliable?

Django REST Framework

DRF serializers vs ModelSerializer

Serializers convert model instances to JSON-ready data and validate incoming data back into objects.

  • Serializer declares every field by hand and you implement create() / update(). ModelSerializer builds fields and validators from the model and implements create/update for you.
  • Output: Serializer(instance).data. Input: Serializer(data=request.data), then is_valid(raise_exception=True), then save().
  • Validation order: field validation, validate_<field>(), then validate(attrs) for cross-field rules. Errors are in .errors, clean data in .validated_data.
  • Useful options: read_only_fields, extra_kwargs, source='author.email', SerializerMethodField, write_only=True for passwords.
  • Nested serializers are read-only by default. Writable nesting needs your own create() / update().
  • many=True wraps the serializer in a ListSerializer. HyperlinkedModelSerializer uses URLs instead of primary keys for relations.

Interview questions

  • Serializer vs ModelSerializer?
  • How do you validate data in a DRF serializer?
  • How do you pass the current user into a serializer?

APIView, generics, ViewSets & routers

DRF stacks abstractions: APIView → GenericAPIView + mixins → concrete generic views → ViewSets wired to URLs by routers.

  • APIView: like a Django CBV, but uses DRF Request / Response, content negotiation, and runs authentication, permissions and throttling before your handler.
  • GenericAPIView adds queryset, serializer_class, get_object(), pagination and filtering. Mixins add list, create, retrieve, update, destroy.
  • Concrete generics: ListCreateAPIView, RetrieveUpdateDestroyAPIView and so on.
  • ViewSets group the actions for one resource. ModelViewSet = full CRUD; ReadOnlyModelViewSet = list + retrieve. Extra endpoints use @action(detail=True, methods=['post']).
  • Routers generate URLs for viewsets. DefaultRouter also adds an API root view; SimpleRouter does not.
  • Override get_queryset() (per-user data) and get_serializer_class() (different serializers per action). Use perform_create() to inject server-side fields.

Interview questions

  • APIView vs ViewSet?
  • What do routers do, and SimpleRouter vs DefaultRouter?
  • How do you add a custom endpoint like /orders/{id}/cancel/ to a ViewSet?

DRF auth, permissions, throttling, pagination & filtering

Authentication identifies the caller, permissions decide access, throttles limit rate, and pagination and filter backends shape list responses.

  • Authentication classes: SessionAuthentication (enforces CSRF), BasicAuthentication, TokenAuthentication (rest_framework.authtoken), JWT via djangorestframework-simplejwt.
  • Permissions: AllowAny, IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly, DjangoModelPermissions. Custom ones subclass BasePermission with has_permission() and has_object_permission().
  • Failed auth → 401 if the first authenticator provides a WWW-Authenticate header (Token, Basic), otherwise 403 (Session). Authenticated but not allowed → 403.
  • Throttling: AnonRateThrottle, UserRateThrottle, ScopedRateThrottle with rates like '100/hour'. State lives in the cache, so use a shared cache (Redis). Returns 429.
  • Pagination: PageNumberPagination (?page=2), LimitOffsetPagination (?limit=&offset=), CursorPagination (opaque cursor, stable under inserts, needs a fixed ordering).
  • Filtering: override get_queryset(), or use backends: DjangoFilterBackend (django-filter, filterset_fields), SearchFilter (?search=), OrderingFilter (?ordering=-price).

Interview questions

  • Authentication vs permissions in DRF?
  • has_permission vs has_object_permission?
  • Session vs Token vs JWT authentication in DRF?
  • Why choose cursor pagination?
  • How does DRF throttling work and what are its limits?

Testing & deployment

Testing & production deployment

Django's test runner gives isolated test databases and a test client; production means Gunicorn/Uvicorn behind a proxy with collected static files and safe settings.

  • TestCase wraps each test in a transaction and rolls back (fast). TransactionTestCase truncates tables (needed to test real commits / on_commit). SimpleTestCase blocks DB access.
  • Use setUpTestData() for class-level fixtures, self.client for full request tests, RequestFactory for calling a view directly, and @override_settings.
  • Useful asserts: assertNumQueries, assertContains, assertRedirects, assertTemplateUsed. DRF adds APIClient, APITestCase and force_authenticate().
  • Many teams use pytest-django (fixtures, @pytest.mark.django_db) and factory_boy for test data instead of JSON fixtures.
  • Deploy: Gunicorn for WSGI (gunicorn mysite.wsgi) or Uvicorn / Daphne for ASGI, behind Nginx or a load balancer that terminates TLS.
  • Release steps: install deps → collectstatic --noinput → migrate (one job, before new code takes traffic) → restart workers. Run check --deploy in CI.
  • DB connections: CONN_MAX_AGE for persistent connections, CONN_HEALTH_CHECKS, PgBouncer, or the native PostgreSQL pool (OPTIONS: {'pool': True}, Django 5.1+ with psycopg 3).

Interview questions

  • TestCase vs TransactionTestCase?
  • How do you deploy a Django app to production?
  • How many Gunicorn workers should you run?