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
- Django is MTV: Model (data + ORM), Template (presentation), View (request → response logic). The framework itself plays the MVC 'controller' through its URL dispatcher.
- A project is the deployable site (settings, root URLconf, WSGI/ASGI entry). An app is a reusable feature package listed in
INSTALLED_APPS. - Request path: server → WSGI/ASGI handler → middleware (top to bottom) → URL resolver → view → middleware (bottom to top) → response.
- QuerySets are lazy: chaining
filter()builds SQL but runs nothing. They hit the DB on iteration,list(),len(),bool(), step slicing orrepr(), then cache the result. Qobjects build OR / NOT conditions.Fobjects refer to a column in the DB, soupdate(stock=F('stock') - 1)is atomic and race-free.aggregate()returns one dict for the whole queryset.annotate()adds a value per row (GROUP BY). Filtering after annotate becomesHAVING.- N+1: one query for the list plus one per row for a relation. Fix with
select_related(FK / one-to-one, SQL JOIN) orprefetch_related(M2M / reverse FK, second query + Python join). queryset.update(),bulk_create()andbulk_update()skipsave()and the save signals. Remember this before relying on signals.transaction.atomic()wraps work in a transaction; nested blocks become savepoints. Usetransaction.on_commit()to send emails or Celery tasks only after commit.null=Trueis about the database column.blank=Trueis about form validation. For strings, preferblank=Truewith an empty string instead of NULL.- Create migrations with
makemigrations, apply them withmigrate, inspect withsqlmigrate. Data migrations useRunPythonwithapps.get_model(), never a direct import. - Define a custom user model (
AbstractUser) at the start of every project and pointAUTH_USER_MODELat it. Changing it later is painful. - CSRF protection is on by default for unsafe methods. The template output is auto-escaped against XSS. The ORM parameterises queries against SQL injection.
- Signals run synchronously inside the same transaction. Prefer an explicit service function or overriding
save()when the logic belongs to your own models. - DRF:
Serializer= validation + conversion,ModelSerializergenerates fields from the model.ModelViewSet+DefaultRoutergives full CRUD URLs in a few lines. - Production:
DEBUG=False,ALLOWED_HOSTS, secret from env,collectstatic, Gunicorn (WSGI) or Uvicorn (ASGI) behind Nginx, andmanage.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
HttpRequestand returns anHttpResponse. - 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 sitecreatesmanage.py,settings.py, the rooturls.py,wsgi.pyandasgi.py.python manage.py startapp blogcreates an app:models.py,views.py,admin.py,apps.py,tests.pyand amigrations/package. Add it toINSTALLED_APPS.- Each app has an
AppConfigclass. Itsready()method is the place to connect signals or do start-up work. manage.pyisdjango-adminwithDJANGO_SETTINGS_MODULEalready 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_MODULEdecides which settings module loads. Read values throughfrom 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. Usere_path()for regex patterns.include('blog.urls')mounts an app's URLconf under a prefix. Setapp_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.methodyourself. - Class-based views (CBV) dispatch by HTTP method (
get(),post()), andas_view()creates a new instance per request, so storing state onselfis 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
LoginRequiredMixinandPermissionRequiredMixin. They must come before the base view in the class list. - Shortcuts:
render(),redirect(),get_object_or_404(),get_list_or_404(). ReturnJsonResponsefor simple JSON.
Interview questions
- When would you choose an FBV over a CBV?
- How does
as_view()work? - How do you restrict an
UpdateViewso 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 optionalthroughmodel for extra columns). on_deleteis required on FKs:CASCADE,PROTECT,RESTRICT,SET_NULL(needsnull=True),SET_DEFAULT,SET(...),DO_NOTHING.related_namenames the reverse accessor (author.books.all()instead ofauthor.book_set.all()).Metaoptions: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 addedCompositePrimaryKey.
Interview questions
- What is the difference between
null=Trueandblank=True? - Explain the
on_deleteoptions. - 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.
makemigrationscompares models to the state built from existing migration files (not the live DB) and writes new operations.migrateapplies unapplied migrations and records them in thedjango_migrationstable.migrate app 0003rolls back to that migration.- Inspect with
showmigrationsandsqlmigrate app 0004(prints the SQL).--fakemarks a migration applied without running it. - Data migrations use
RunPython(forwards, backwards). Get models withapps.get_model('shop', 'Book'), the historical version, not by importing. - Two developers creating migration 0005 on different branches causes a conflict.
makemigrations --mergecreates a merge migration. squashmigrationscombines a long chain into one file to speed up test DB creation.
Interview questions
- What is the difference between
makemigrationsandmigrate? - 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 ofif qs:,count()instead oflen(qs)when you do not need the rows. A slice likeqs[:10]becomesLIMITand stays lazy. get()raisesDoesNotExistorMultipleObjectsReturned.first()returnsNone.get_or_create()andupdate_or_create()return(obj, created).- Keyword lookups are ANDed. Use
Qfor|(OR),&and~(NOT). UseFto 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 customQuerySetand expose it withQuerySet.as_manager()so they chain. - Use
iterator()for huge result sets (no cache, streams in chunks) andvalues()/values_list(flat=True)when you do not need model instances.
Interview questions
- What does it mean that QuerySets are lazy?
- What are
QandFobjects? count()vslen(), andexists()vsif 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 annattribute. You can thenfilter(n__gte=2)(SQLHAVING) ororder_by('-n').- Order matters:
filter()beforeannotate()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. Usedistinct=Trueor subqueries. Subquery+OuterRefembed a correlated subquery;Exists()is ideal for 'has any' checks. UseCoalesceto turn NULL into a default.values('field').annotate(...)groups by that field, likeGROUP BY field.
Interview questions
- Difference between
aggregate()andannotate()? - 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.nameruns 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 withWHERE 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 thePrefetchinstead. 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,
assertNumQueriesin 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_relatedandprefetch_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 callsave()or sendpre_save/post_save. Options:ignore_conflicts,update_conflicts.bulk_update(objs, ['price'])andqueryset.update(...)run UPDATE statements with nosave()and no signals.auto_nowfields are not touched byupdate().queryset.delete()deletes in SQL but still emulates cascades and sendspre_delete/post_deleteper object.- By default Django runs in autocommit mode: each query commits on its own.
ATOMIC_REQUESTS = Truewraps every view in a transaction. transaction.atomic()(decorator orwith) commits on success and rolls back on exception. Nestedatomicblocks create savepoints.select_for_update()takes row locks (SELECT ... FOR UPDATE) until the transaction ends. It must run insideatomic. Options:nowait,skip_locked,of.transaction.on_commit(fn)runsfnonly after the outer transaction commits. Use it for emails, cache invalidation and Celery tasks.
Interview questions
- Why might
bulk_createorupdate()break your app's logic? - How does
transaction.atomicbehave when nested? - Two users buy the last item at the same time. How do you prevent overselling?
- What is
transaction.on_commitfor?
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_responseand returns a callable taking a request. Code beforeget_response(request)runs on the way in, code after it runs on the way out. - Order in
MIDDLEWAREmatters: 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. AuthenticationMiddlewareneeds the session, so it must come afterSessionMiddleware. It setsrequest.userlazily.- 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_viewgive 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(withcreated),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 inAppConfig.ready(). Usedispatch_uidto 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
Profilewhen a third-partyUseris created), or library hooks. - Prefer explicit code for your own models: override
save(), or call a service function likecreate_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.
|safeandmark_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 intemplatetags/. - 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, thenclean_<field>()methods, thenclean()for cross-field rules. Read data fromcleaned_data. - A ModelForm builds fields from a model (
Meta.model,Meta.fields), validates model constraints and saves withsave().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 throughAUTHENTICATION_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 assignuser.passworddirectly. - Custom user: extend
AbstractUserto add fields, orAbstractBaseUser+PermissionsMixinfor full control (e.g. email login). SetAUTH_USER_MODELbefore the first migration. - Reference the user with
get_user_model()in code andsettings.AUTH_USER_MODELin FKs. - Each model gets
add,change,delete,viewpermissions. Check withuser.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+)LoginRequiredMiddlewarewith@login_not_requiredon public views. - Admin:
@admin.register(Model)with aModelAdmin: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?
AbstractUservsAbstractBaseUser?- 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 areHttpOnlyby default. - CSRF:
CsrfViewMiddlewarechecks POST/PUT/PATCH/DELETE for a token (form fieldcsrfmiddlewaretokenorX-CSRFTokenheader) matching thecsrftokencookie, and checksOriginfor HTTPS requests. - Cross-origin front ends must be listed in
CSRF_TRUSTED_ORIGINS. Use@csrf_exemptonly 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_HEADERbehind a proxy. - SQL injection: the ORM parameterises everything. With
raw()orcursor.execute(), pass values asparams, 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, andSTATIC_ROOTas the target ofcollectstatic. UseManifestStaticFilesStoragefor 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
STORAGESsetting (defaultandstaticfileskeys).
Interview questions
- What caching levels does Django offer?
- Static files vs media files?
- What does
collectstaticdo?
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 defviews 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 raisesSynchronousOnlyOperation. - Wrap sync code with
sync_to_async()(runs in a thread) and async code withasync_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 beatschedules 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 hasdelay_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.
Serializerdeclares every field by hand and you implementcreate()/update().ModelSerializerbuilds fields and validators from the model and implements create/update for you.- Output:
Serializer(instance).data. Input:Serializer(data=request.data), thenis_valid(raise_exception=True), thensave(). - Validation order: field validation,
validate_<field>(), thenvalidate(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=Truefor passwords. - Nested serializers are read-only by default. Writable nesting needs your own
create()/update(). many=Truewraps the serializer in aListSerializer.HyperlinkedModelSerializeruses 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 DRFRequest/Response, content negotiation, and runs authentication, permissions and throttling before your handler.GenericAPIViewaddsqueryset,serializer_class,get_object(), pagination and filtering. Mixins addlist,create,retrieve,update,destroy.- Concrete generics:
ListCreateAPIView,RetrieveUpdateDestroyAPIViewand 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.
DefaultRouteralso adds an API root view;SimpleRouterdoes not. - Override
get_queryset()(per-user data) andget_serializer_class()(different serializers per action). Useperform_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 viadjangorestframework-simplejwt. - Permissions:
AllowAny,IsAuthenticated,IsAdminUser,IsAuthenticatedOrReadOnly,DjangoModelPermissions. Custom ones subclassBasePermissionwithhas_permission()andhas_object_permission(). - Failed auth → 401 if the first authenticator provides a
WWW-Authenticateheader (Token, Basic), otherwise 403 (Session). Authenticated but not allowed → 403. - Throttling:
AnonRateThrottle,UserRateThrottle,ScopedRateThrottlewith 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_permissionvshas_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.
TestCasewraps each test in a transaction and rolls back (fast).TransactionTestCasetruncates tables (needed to test real commits /on_commit).SimpleTestCaseblocks DB access.- Use
setUpTestData()for class-level fixtures,self.clientfor full request tests,RequestFactoryfor calling a view directly, and@override_settings. - Useful asserts:
assertNumQueries,assertContains,assertRedirects,assertTemplateUsed. DRF addsAPIClient,APITestCaseandforce_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. Runcheck --deployin CI. - DB connections:
CONN_MAX_AGEfor persistent connections,CONN_HEALTH_CHECKS, PgBouncer, or the native PostgreSQL pool (OPTIONS: {'pool': True}, Django 5.1+ with psycopg 3).
Interview questions
TestCasevsTransactionTestCase?- How do you deploy a Django app to production?
- How many Gunicorn workers should you run?