Skip to main content

OneHub Technical Interview Masterclass: Django & DRF

Total Questions: 50 Curriculum: Core Fundamentals (60), Applied Intermediate (70), Principal Advanced (70+)


🏗️ Section 1: Core Fundamentals​

Q1: Describe the Django Request-Response Cycle.​

Technical Answer:

  1. Request enters the web server (WSGI/ASGI).
  2. Middleware executes (pre-view).
  3. URL Dispatcher matches the path.
  4. View logic executes (Interaction with Model/DB).
  5. Template/DRF Serializer renders response.
  6. Middleware executes (post-view).
  7. Response sent back to server.

Code/Syntax Justification:

# Custom Middleware
def simple_middleware(get_response):
def middleware(request):
# Before view
response = get_response(request)
# After view
return response
return middleware

🔍 Behind the Question: Framework flow and extensibility points. ❌ The Red Flags: Putting business logic in the wrong layer (e.g., templates).

Q2: What is Django ORM, and how does it map Python objects to database tables?​

Technical Answer: Django ORM is an abstraction layer that lets developers work with database records as Python objects. A model class maps to a table, each field maps to a column, and QuerySets represent lazy database queries. The ORM handles SQL generation, escaping, and basic joins, allowing developers to focus on domain logic while still writing efficient queries when needed.

Code/Syntax Justification:

class User(models.Model):
email = models.EmailField(unique=True)

user = User.objects.create(email="a@example.com")

🔍 Behind the Question: Testing ORM fundamentals and database abstraction knowledge. ❌ The Red Flags: Thinking ORM removes the need to understand SQL.

Q3: What causes the N+1 query problem in Django/DRF, and how do you fix it?​

Technical Answer: N+1 happens when an application performs one query to fetch a parent object list and then one query per parent to fetch related data. This becomes expensive at scale. Django fixes it using select_related() for single-valued relations and prefetch_related() for many-valued relations, which batch queries and assemble the relation in memory.

Code/Syntax Justification:

posts = Post.objects.select_related("author").prefetch_related("comments")

🔍 Behind the Question: Testing performance awareness and query optimization. ❌ The Red Flags: Rendering serializers without understanding query counts.

Q4: What is Django middleware and what can it do?​

Technical Answer: Middleware is a chain of hooks that process requests before they reach views and responses before they return. Common uses: authentication, logging, CORS headers, rate limiting, request ID injection, and security headers. Each middleware can short-circuit the chain (e.g., reject a request).

Code/Syntax Justification:

# settings.py
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"corsheaders.middleware.CorsMiddleware",
"myapp.middleware.RequestIDMiddleware",
]

🔍 Behind the Question: Request lifecycle and cross-cutting concerns. ❌ The Red Flags: Doing DB work in middleware per request without caching.

Q5: How do you secure a Django/DRF API?​

Technical Answer: Use authentication (Token/JWT/Session) + permission classes (IsAuthenticated, IsAdminUser, custom object-level permissions), enforce HTTPS, set SECURE_* settings, validate input via DRF serializers, rate-limit login endpoints, and avoid exposing DEBUG in production.

Code/Syntax Justification:

# settings.py
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework_simplejwt.authentication.JWTAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated",
],
"DEFAULT_THROTTLE_RATES": {"login": "5/min"},
}

🔍 Behind the Question: OWASP basics applied to Django. ❌ The Red Flags: AllowAny endpoints without auth; weak password policies.

Q6: How do you design DRF serializers for nested relationships?​

Technical Answer: Use PrimaryKeyRelatedField for write (efficient), nested serializers read-only for display, or HyperlinkedModelSerializer. Avoid recursive depth explosion by splitting into read/write serializers. Use depth sparingly — it can double queries without select_related.

Code/Syntax Justification:

class OrderSerializer(serializers.ModelSerializer):
items = OrderItemSerializer(many=True, read_only=True)
class Meta:
model = Order
fields = ["id", "user", "items", "total"]

🔍 Behind the Question: Serialization design and query efficiency. ❌ The Red Flags: Nested write serializers creating N+1 inserts.

Q7: What is Django Signals and when should you avoid them?​

Technical Answer: Signals (post_save, pre_delete) let decoupled apps react to model lifecycle events — e.g., send a welcome email after user creation. Avoid: heavy logic that should live in services/tasks, operations that must be transactional (signals run in the same transaction by default), and implicit behavior that surprises future readers.

Code/Syntax Justification:

@receiver(post_save, sender=User)
def send_welcome(sender, instance, created, **kwargs):
if created:
# Queue the task only after the transaction commits, or the worker
# may run before the user row is visible.
transaction.on_commit(lambda: send_mail.delay(instance.email))

🔍 Behind the Question: Decoupling vs implicit control flow. ❌ The Red Flags: Doing slow work synchronously in signals.

Q8: How do you implement caching in Django?​

Technical Answer: Cache API (cache.set/get), per-view caching (@cache_page), or template fragment caching. Use Redis as the cache backend in production. Set TTLs, invalidate on write, and cache expensive queries or computed data — never cache per-user data globally without keying it.

Code/Syntax Justification:

from django.core.cache import cache

def stats(request):
data = cache.get("stats")
if data is None:
data = expensive_query()
cache.set("stats", data, 300) # 5 min TTL
return JsonResponse(data)

🔍 Behind the Question: Performance optimization patterns. ❌ The Red Flags: Caching everything without TTL; stale reads after writes.

Technical Answer: select_related: JOIN at query time for FK/OneToOne — one query, works for forward relationships. prefetch_related: one extra query per prefetched relation (not per object), joined in Python — works for ManyToMany and reverse relations. Choose by relationship direction; combine for complex graphs.

Code/Syntax Justification:

# FK: JOIN in one query
orders = Order.objects.select_related("user").all()
# M2M / reverse: separate query then merge
posts = Post.objects.prefetch_related("tags", "comments").all()

🔍 Behind the Question: ORM query efficiency. ❌ The Red Flags: Using select_related on reverse relations (raises/ignored).

Q10: How do you handle transactions in Django?​

Technical Answer: Use transaction.atomic() blocks — either all operations commit or all roll back. Nest via savepoints. Wrap only what must be atomic; keep I/O and slow work out. Use transaction.on_commit() to run side effects after commit (email, cache invalidation) so they don't fire on rollback.

Code/Syntax Justification:

from django.db import transaction

with transaction.atomic():
order = Order.objects.create(...)
Payment.objects.create(order=order, ...) # rollback if fails
transaction.on_commit(lambda: notify_customer(order.id))

🔍 Behind the Question: Data integrity under failures. ❌ The Red Flags: Doing email/HTTP inside atomic blocks.

Q11: How do you do role-based access control (RBAC) in Django?​

Technical Answer: Model-level: Django Groups + Permissions (has_perm, model permissions). Object-level: custom permission classes checking ownership (e.g., owner == request.user), or libraries like django-guardian. Combine: group for roles, object checks for per-record access.

Code/Syntax Justification:

class IsOwner(BasePermission):
def has_object_permission(self, request, view, obj):
return obj.user == request.user

class OrderViewSet(ModelViewSet):
permission_classes = [IsAuthenticated, IsOwner]

🔍 Behind the Question: Authorization design. ❌ The Red Flags: Checking roles only in views, duplicating permission logic.

Q12: What is Django REST Framework throttling and how do you use it?​

Technical Answer: Throttling limits request rates per user/IP/anonymous scope to prevent abuse. Define rate strings ("10/min", "100/hour"), set global defaults, and override per-view. Useful for login, search, and public endpoints.

Code/Syntax Justification:

REST_FRAMEWORK = {
"DEFAULT_THROTTLE_CLASSES": [
"rest_framework.throttling.UserRateThrottle",
"rest_framework.throttling.AnonRateThrottle",
],
"DEFAULT_THROTTLE_RATES": {"user": "1000/day", "anon": "100/day"},
}

🔍 Behind the Question: API abuse protection. ❌ The Red Flags: No throttling on auth endpoints (brute force).


Senior / Principal — Real World Scenarios​

Q13: N+1 query explosion in a DRF list endpoint​

Level: Senior

Scenario: A DRF ListAPIView returns 100 orders. Each order serializer nests the customer and items. The page loads in 8 seconds and database CPU spikes.

Impact: Slow API responses. Database overload. Poor user experience.

Root Cause: The view runs 1 query for orders, then 1 query per order to fetch customer, then 1 per order to fetch items = 1 + 100 + 100 = 201 queries (N+1).

Simple explanation: You ask for 100 receipts. For each receipt, you make a separate phone call to ask who bought it and what they bought. 201 phone calls instead of 1.

Technical Answer:

  1. Use select_related("customer") for single-valued foreign keys (SQL JOIN).
  2. Use prefetch_related("items") for many-valued relations (separate query + Python join).
  3. Confirm with Django Debug Toolbar or django-debug-toolbar query count.
  4. Add database indexes on foreign key columns.

Code/Syntax Justification:

class OrderViewSet(ModelViewSet):
queryset = Order.objects.select_related("customer").prefetch_related("items__product")
serializer_class = OrderSerializer

Workflow Diagram:

Without fix: With select_related + prefetch_related:
1 query: orders 1 query: orders (JOIN customer)
100 queries: customers 1 query: items (all at once)
100 queries: items Python joins items to orders in memory
Total: 201 queries Total: 3 queries

🔍 Behind the Question: Query optimization, N+1 detection, select_related vs prefetch_related.

Red flags: Serializing nested relations without prefetch_related; not measuring query count.


Q14: Slow admin page with thousands of rows​

Level: Senior

Scenario: The Django admin User list page times out after the table grows to 200k rows. The admin queries all fields and orders by -date_joined.

Impact: Admin unusable. Operators cannot manage users. Timeouts.

Root Cause: Django admin fetches all columns (SELECT *) and counts all rows for pagination (SELECT COUNT(*)), which is expensive on large tables without proper indexing.

Simple explanation: Reading every page of a 200k-row ledger just to show the first 100 names.

Technical Answer:

  1. Use list_display with only needed fields (avoid SELECT * where possible via defer/only).
  2. Add database index on -date_joined for ordering.
  3. Use raw_id_fields or autocomplete_fields for foreign keys instead of dropdowns.
  4. Override get_queryset to select_related/prefetch_related and limit fields.

Code/Syntax Justification:

class UserAdmin(admin.ModelAdmin):
list_display = ("email", "date_joined", "is_active")
list_select_related = ("profile",)
autocomplete_fields = ("groups",)
ordering = ("-date_joined",)

def get_queryset(self, request):
qs = super().get_queryset(request)
# Don't combine .only() with select_related("profile") unless the relation is
# included in .only(); a deferred field that is also traversed raises FieldError.
return qs.select_related("profile")

Workflow Diagram:

Admin page request
|
v
Without fix: SELECT * FROM users ORDER BY -date_joined LIMIT 100
+ SELECT COUNT(*) FROM users
-> full table scan, slow
|
v
With fix: SELECT email, date_joined, is_active FROM users
ORDER BY -date_joined LIMIT 100 (uses index)
+ count optimized
-> fast

🔍 Behind the Question: Admin performance, indexing, query field selection.

Red flags: list_display with many related fields causing N+1; no index on ordering field; raw_id_fields missing for large FKs.


Q15: Database writes fail under concurrent order placement​

Level: Principal

Scenario: During a flash sale, 5000 users place orders for the same limited item at the same time. Overselling occurs — more orders created than stock available.

Impact: Financial loss. Customer complaints. Inventory data corrupt.

Root Cause: Read-then-write without locking. Two requests both read stock=1, both proceed to create orders, stock goes negative.

Simple explanation: Two shoppers both see "1 left on shelf." Both grab it and check out. Only one item existed.

Technical Answer:

  1. Use select_for_update() within a transaction to pessimistically lock the stock row.
  2. Wrap in transaction.atomic() so either both read+write succeed or neither.
  3. Add a CheckConstraint on stock >= 0 at the database level as a safety net.
  4. Retry on DatabaseError/OperationalError (deadlock/serialization failure).

Code/Syntax Justification:

from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import F

@transaction.atomic
def place_order(item_id, user_id):
item = Item.objects.select_for_update().get(id=item_id)
if item.stock <= 0:
raise ValidationError("Out of stock")
item.stock = F("stock") - 1
item.save()
Order.objects.create(item=item, user_id=user_id)
item.refresh_from_db(fields=["stock"]) # replace the F() expression with the new value
return item

Workflow Diagram:

Request A Request B
| |
v v
SELECT FOR UPDATE item SELECT FOR UPDATE item (blocks)
lock stock=1 (waits for A)
| |
v v
stock>0, decrement to 0 A commits, lock released
save order B reads stock=0 -> "Out of stock"
| |
v v
COMMIT No oversell

🔍 Behind the Question: Pessimistic locking, select_for_update, transaction atomicity, database constraints.

Red flags: get() then save() without lock; no transaction; no DB-level CheckConstraint.


Q16: DRF view returns 500 on unhandled exception — no error tracking​

Level: Senior

Scenario: A DRF API raises an unhandled exception (e.g., KeyError). Django returns 500 with no useful context. The team does not know it happened until customers complain.

Impact: Silent failures. Debugging is slow. Revenue impact undetected.

Root Cause: No centralized exception handling, no structured logging, no error tracking integration (Sentry), no correlation IDs.

Simple explanation: A machine breaks and no alarm rings. You only find out when someone reports it.

Technical Answer:

  1. Use Django REST Framework's exception_handler to standardize error responses.
  2. Integrate Sentry SDK to capture exceptions with context (user, request, trace).
  3. Add correlation IDs (middleware) so logs across services can be traced.
  4. Log errors with structlog or Django logging, including request ID and user.

Code/Syntax Justification:

# middleware.py
import uuid
class CorrelationIDMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.id = str(uuid.uuid4())
response = self.get_response(request)
response["X-Request-ID"] = request.id
return response

# settings.py - Sentry
import sentry_sdk
sentry_sdk.init(dsn="https://...", traces_sample_rate=1.0)

Workflow Diagram:

Unhandled exception in view
|
v
Without fix: Django 500, no context, team unaware
|
v
With fix: Correlation ID assigned
-> exception_handler standardizes response
-> Sentry captures with request ID + user
-> team alerted, can trace logs by ID

🔍 Behind the Question: Error observability, structured logging, exception handling, correlation IDs.

Red flags: Letting exceptions bubble to raw 500; no error tracking; no request ID.


Q17: Media file served directly by Django in production​

Level: Principal

Scenario: User-uploaded product images are served by Django (django.views.static.serve) in production. Each image request ties up a Django worker. Under load, workers exhaust and the API becomes unresponsive.

Impact: API downtime under media traffic. Wasted application server capacity.

Root Cause: Django is an application framework, not an efficient file server. Media should be served by a web server (Nginx) or object storage (S3) directly.

Simple explanation: Using a chef to deliver takeout bags instead of a delivery driver. The chef cannot cook while delivering.

Technical Answer:

  1. Serve media via Nginx location /media/ { alias ...; } or via S3/CloudFront signed URLs.
  2. Django only handles the upload (write) and metadata (DB), not the download (read).
  3. Use X-Accel-Redirect (Nginx) or X-Sendfile for protected media so Django authorizes but Nginx serves.
  4. Set cache headers (Cache-Control) on media for CDN/browser caching.

Code/Syntax Justification:

# Protected media: Django authorizes, Nginx serves
from django.http import HttpResponse, HttpResponseForbidden

def protected_media(request, path):
if not request.user.has_access(path):
return HttpResponseForbidden()
response = HttpResponse()
response["X-Accel-Redirect"] = f"/protected-media/{path}"
return response
# nginx
location /protected-media/ {
internal;
alias /var/www/media/;
}

Workflow Diagram:

Without fix: Client -> Django worker -> read file from disk -> response
(worker blocked during file read)
|
v
With fix: Client -> Django (authorize) -> X-Accel-Redirect -> Nginx serves file
(Django worker freed immediately)

🔍 Behind the Question: Static/media serving, application vs web server responsibilities, X-Accel-Redirect.

Red flags: django.views.static.serve in production; Django serving large files; no CDN/object storage.


Q18: Celery task silently fails — orders not processed​

Level: Principal

Scenario: Orders are created and a Celery task process_payment is enqueued. The task never runs or fails silently. Orders sit in "pending" forever. Revenue lost.

Impact: Unprocessed orders. Customer dissatisfaction. Revenue loss.

Root Cause: No task result backend, no retry policy, no monitoring on task failures, worker not running, or task raises exception without being caught.

Simple explanation: You drop a letter in a mailbox but never check if it was delivered. If the mail truck never comes, the letter sits forever.

Technical Answer:

  1. Configure Celery task_acks_late and task_reject_on_worker_lost so tasks are redelivered if a worker crashes mid-task (they do not retry tasks that raise exceptions; that needs explicit retries).
  2. Set max_retries and default_retry_delay with exponential backoff.
  3. Use a result backend (Redis/DB) and monitor task states (SUCCESS/FAILURE/RETRY).
  4. Add Flower or Celery events + alerting on failure rate.
  5. Idempotent tasks so retries do not double-charge.

Code/Syntax Justification:

@app.task(bind=True, max_retries=3, default_retry_delay=60, acks_late=True)
def process_payment(self, order_id):
try:
order = Order.objects.get(id=order_id)
payment_gateway.charge(order)
except Exception as exc:
raise self.retry(exc=exc, countdown=60 * (2 ** self.request.retries))

Workflow Diagram:

Order created -> enqueue process_payment
|
v
[Celery worker picks up task]
|
+-- success --> mark order processed
|
+-- failure --> retry with backoff (max 3)
|
+-- still failing --> FAILURE state + alert

🔍 Behind the Question: Async task reliability, retries, result backend, monitoring, idempotency.

Red flags: No retry policy; fire-and-forget tasks for business-critical work; no failure alerting.


Q19: Django DEBUG = True in production leaking secrets​

Level: Senior

Scenario: A deployment leaves DEBUG = True in production. Error pages display stack traces with environment variables, secret keys, and SQL queries to attackers.

Impact: Secret exposure. Attackers can exploit detailed error info. Compliance violation.

Root Cause: Settings not environment-aware. DEBUG hardcoded to True or not overridden in production settings.

Simple explanation: Leaving the house key under the mat with a sign "come in." Anyone who finds it gets in.

Technical Answer:

  1. Use environment variables for all settings (django-environ or pydantic-settings).
  2. DEBUG = False in production by default.
  3. ALLOWED_HOSTS strictly set to production domains.
  4. Never commit .env or settings with secrets to version control.
  5. Use SECRET_KEY from env, rotated periodically.

Code/Syntax Justification:

# settings.py
import environ
env = environ.Env(DEBUG=(bool, False))
DEBUG = env("DEBUG")
SECRET_KEY = env("SECRET_KEY")
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=[])

Workflow Diagram:

Error in production view
|
+-- DEBUG=True --> detailed HTML traceback with secrets leaked
|
+-- DEBUG=False --> generic 500 page, error logged to Sentry

🔍 Behind the Question: Security hygiene, environment-based configuration, secret management.

Red flags: DEBUG = True committed to production; secrets in settings.py; ALLOWED_HOSTS = ["*"].


Q20: Database migration locks table during deploy​

Level: Principal

Scenario: A deploy adds a column with a volatile default (e.g. a random or time-based value) to a 50-million-row table. ALTER TABLE rewrites the whole table while holding an ACCESS EXCLUSIVE lock. (Since PostgreSQL 11, a constant default no longer rewrites the table.) The site is read-only or down for 20 minutes.

Impact: Extended downtime. Failed deploy. Rollback stress.

Root Cause: Non-backward-compatible migration that locks the table. Not using AddField with db_default carefully or not running migrations separately from code deploy.

Simple explanation: Replacing the foundation of a building while people are inside. Everyone must leave until it's done.

Technical Answer:

  1. Use backward-compatible migrations: add a nullable column first (a fast, metadata-only change, though it still takes a brief ACCESS EXCLUSIVE lock), backfill in batches, then make it non-null in a later deploy.
  2. Run migrations separately from code deploy (migrate first, then deploy code that uses the new column).
  3. Build indexes with AddIndexConcurrently (from django.contrib.postgres.operations) in a migration with atomic = False.
  4. Set a short lock_timeout for migrations and retry, so a DDL statement waiting behind a long transaction fails fast instead of blocking every query queued behind it.
  5. Test migration on production-sized staging data.

Code/Syntax Justification:

# Backward-compatible: add nullable field first
class Migration(migrations.Migration):
operations = [
migrations.AddField(
model_name="order",
name="status",
field=models.CharField(max_length=20, null=True, blank=True),
),
]
# Later migration backfills and sets null=False

Workflow Diagram:

Bad deploy: Safe deploy:
ALTER TABLE add column (lock) 1. Add nullable column (brief lock)
site down 20 min 2. Deploy code (writes to nullable col)
3. Backfill data in batches
4. Set null=False, add default
No downtime

🔍 Behind the Question: Zero-downtime migrations, backward compatibility, lock avoidance.

Red flags: ALTER TABLE on huge table during deploy; adding non-null column with default directly; running migrate and deploy simultaneously.


ORM Deep Dive​

Q21: What does it mean that QuerySets are lazy, and when are they evaluated and cached?​

Technical Answer: Building a QuerySet (filter, exclude, order_by, annotate) runs no SQL. Each call returns a new QuerySet object. SQL runs only when the QuerySet is evaluated: by iteration, list(), len(), bool()/if qs:, repr(), pickling, or slicing with a step. After a full evaluation the rows are stored in the QuerySet's result cache, so iterating the same object again costs no new query.

Things that do not fill the cache, or that bypass it:

  • Slicing or indexing an unevaluated QuerySet (qs[0], qs[:10]) runs a LIMIT query every time.
  • .count(), .exists(), .first(), .get(), .aggregate() always run their own query.
  • .all() returns a new QuerySet with an empty cache, so user.orders.all() in a loop queries each time unless prefetched.
  • .iterator() streams rows and never caches them.

Practical rules: use .exists() when you only need a yes/no, use len(qs) only if you will also use the rows, and keep the evaluated QuerySet in a variable instead of re-building it.

Code/Syntax Justification:

from shop.models import Order

qs = Order.objects.filter(status="paid") # no query
qs = qs.exclude(total=0).order_by("-created_at") # still no query

orders = list(qs) # query 1: rows now in qs's result cache
total = len(qs) # no query (cache)
first = qs[0] # no query: indexing an evaluated QuerySet uses the cache

fresh = Order.objects.filter(status="paid")
fresh[0] # query: ... LIMIT 1
fresh[0] # query again: slicing an unevaluated QuerySet is not cached

if Order.objects.filter(status="failed").exists(): # SELECT 1 ... LIMIT 1
pass

for order in qs: # no query: same evaluated object
order.customer # one query PER ORDER unless select_related("customer")

🔍 Behind the Question: Understanding when SQL runs is the basis of every Django performance discussion (N+1, memory, duplicate queries). ❌ The Red Flags: if qs: followed by qs.count() and then iteration (three queries); len(Model.objects.all()) to count rows; assuming .all() re-uses a cache.


Q22: How do F expressions and Q objects work, and why do they matter?​

Technical Answer:

  • F("field") refers to a column's value inside the database. update(stock=F("stock") - 1) compiles to SET stock = stock - 1, which is atomic at the row level and avoids the read-modify-write race of obj.stock -= 1; obj.save(). F() also compares two columns (filter(stock__lt=F("reorder_level"))). After obj.field = F(...) followed by obj.save(), the Python attribute still holds the expression. Call refresh_from_db() before reading it, and don't save the same instance again, or the increment is applied twice.
  • Q(...) wraps a condition so you can combine conditions with | (OR), & (AND), ~ (NOT) and, since Django 4.2, ^ (XOR). Positional Q arguments must come before keyword arguments in filter(). You can build dynamic filters by accumulating Q objects.

Code/Syntax Justification:

from django.db.models import F, Q

from shop.models import Order, Product

# Atomic decrement, no race between read and write
Product.objects.filter(pk=42, stock__gt=0).update(stock=F("stock") - 1)

# Column-to-column comparison
needs_reorder = Product.objects.filter(stock__lt=F("reorder_level"))

# OR / NOT, positional Q before keyword args
orders = Order.objects.filter(
Q(status="paid") | Q(status="refunded"),
~Q(customer__is_staff=True),
total__gte=100,
)

# Dynamic search across several fields
def search_products(terms: list[str]):
condition = Q()
for term in terms:
condition |= Q(name__icontains=term) | Q(sku__iexact=term)
return Product.objects.filter(condition)

# Instance-level F(): refresh before reading
product = Product.objects.get(pk=42)
product.views = F("views") + 1
product.save(update_fields=["views"])
product.refresh_from_db(fields=["views"])

🔍 Behind the Question: Concurrency safety (lost updates) and expressing complex filters without raw SQL. ❌ The Red Flags: obj.count += 1; obj.save() under concurrent traffic; string-building SQL for OR conditions; reading an attribute that still holds an F() expression.


Q23: What is the difference between annotate() and aggregate(), and what is the multiple-join counting trap?​

Technical Answer:

  • aggregate() collapses the whole QuerySet into one dict ({"revenue": Decimal(...)}). It is terminal.
  • annotate() adds a computed value per row (a GROUP BY for aggregates). The result is still a chainable QuerySet.
  • Order matters: filter() before annotate() restricts which related rows are aggregated. filter() after annotate() on the annotated value becomes HAVING.
  • Use filter=Q(...) inside an aggregate for conditional aggregates, and default= (Django 4.0+) instead of getting None for empty sets.
  • Trap: annotating aggregates over two different multi-valued relations in one query (Count("orders"), Count("tickets")) joins both tables, multiplies the rows, and inflates every result. Count(..., distinct=True) fixes counts but not sums. Use Subquery + OuterRef per relation instead.

Code/Syntax Justification:

from django.db.models import Avg, Count, OuterRef, Q, Subquery, Sum
from django.db.models.functions import Coalesce

from crm.models import Customer, Ticket
from shop.models import Order

# One dict for the whole table
stats = Order.objects.filter(status="paid").aggregate(
revenue=Sum("total", default=0), avg_order=Avg("total")
)

# Per-row values + HAVING
top_customers = (
Customer.objects.annotate(
paid_orders=Count("orders", filter=Q(orders__status="paid")),
paid_total=Sum("orders__total", filter=Q(orders__status="paid"), default=0),
)
.filter(paid_orders__gte=5) # HAVING COUNT(...) >= 5
.order_by("-paid_total")
)

# Safe second aggregate via a correlated subquery (no join multiplication)
open_tickets = (
Ticket.objects.filter(customer=OuterRef("pk"), status="open")
.order_by()
.values("customer")
.annotate(c=Count("pk"))
.values("c")
)
customers = Customer.objects.annotate(
order_count=Count("orders"),
open_ticket_count=Coalesce(Subquery(open_tickets), 0),
)

# Latest related value per row
latest_order = Order.objects.filter(customer=OuterRef("pk")).order_by("-created_at")
customers = customers.annotate(last_order_at=Subquery(latest_order.values("created_at")[:1]))

🔍 Behind the Question: Whether the candidate can push reporting work into SQL correctly, and knows the join-multiplication bug that silently produces wrong numbers. ❌ The Red Flags: Computing aggregates in Python loops; two Count()s over different reverse relations without checking the numbers; forgetting .order_by() in grouped subqueries when the model has Meta.ordering.


Technical Answer: prefetch_related("books") loads all related rows with default ordering. A Prefetch("books", queryset=..., to_attr=...) object lets you:

  • Filter and order the prefetched rows (only published books, newest first).
  • Chain select_related inside the prefetch queryset, avoiding a second N+1 one level down.
  • Store results on a plain list attribute with to_attr, so the intent is explicit and the cache is easy to find.

Key pitfall: calling .filter(), .order_by() or .exclude() on a prefetched related manager (author.books.filter(...)) ignores the prefetch and runs a new query per object. Do the filtering in the Prefetch queryset. For a list of already-loaded instances, use prefetch_related_objects(instances, ...).

Code/Syntax Justification:

from django.db.models import Prefetch, prefetch_related_objects

from library.models import Author, Book, Review

published_books = (
Book.objects.filter(is_published=True)
.select_related("publisher")
.prefetch_related( # nested Prefetch: attaches to the same Book instances
Prefetch("reviews", queryset=Review.objects.filter(rating__gte=4), to_attr="good_reviews")
)
.order_by("-published_at")
)

authors = Author.objects.prefetch_related(
Prefetch("books", queryset=published_books, to_attr="published_books"),
)

for author in authors: # 3 queries total, regardless of row count
for book in author.published_books:
print(book.publisher.name, len(book.good_reviews))

# Anti-pattern: bypasses the prefetch -> one query per author
# for author in Author.objects.prefetch_related("books"):
# author.books.filter(is_published=True)

# Prefetch onto instances you already have in a list
some_authors = list(Author.objects.filter(country="NP"))
prefetch_related_objects(some_authors, "books")

🔍 Behind the Question: Fine-grained control of query shape in real serializers, beyond knowing that prefetch_related exists. ❌ The Red Flags: Filtering on the related manager inside a loop; prefetching entire large relations when only a subset is shown.


Q25: When do you use only(), defer(), values(), values_list() and iterator()?​

Technical Answer:

  • only("a", "b") / defer("big_field") still return model instances but load fewer columns. Accessing a deferred field later triggers one extra query per instance, which is a hidden N+1. Use them only when you know exactly which fields the code touches.
  • values() / values_list() return dicts or tuples instead of model instances. They are cheaper to build and have no lazy-loading surprises, which makes them ideal for exports, reports and IDs (values_list("id", flat=True)). No model methods or signals are involved.
  • iterator(chunk_size=...) streams rows from the database without filling the result cache, so memory stays flat for large scans. On PostgreSQL it uses a server-side cursor. Since Django 4.1, iterator(chunk_size=...) also honours prefetch_related(), per chunk.
  • Behind PgBouncer in transaction-pooling mode, server-side cursors break. Set DISABLE_SERVER_SIDE_CURSORS = True for that database, or batch by primary key instead.

Code/Syntax Justification:

from shop.models import Order

# IDs only - no model instances at all
paid_ids = list(Order.objects.filter(status="paid").values_list("id", flat=True))

# Lightweight rows for an export
rows = Order.objects.filter(status="paid").values("id", "total", "customer__email")

# Instances with fewer columns (careful: touching other fields = extra query each)
orders = Order.objects.only("id", "status", "total")

# Stream a large table with constant memory
for order in Order.objects.filter(status="paid").iterator(chunk_size=2000):
order.total # process one at a time; nothing accumulates in a cache

🔍 Behind the Question: Memory and query-count awareness for list endpoints, admin pages and batch jobs. ❌ The Red Flags: only() followed by templates or serializers that touch deferred fields; loading full model instances just to collect IDs; .all() over millions of rows in a management command.


Q26: How do you declare constraints and indexes in Model Meta?​

Technical Answer: Put data-integrity rules in the database, not only in Python validation, so that concurrent requests, scripts and admin edits can't bypass them.

  • UniqueConstraint: supports condition= (a partial unique index, for example "one active subscription per user"; supported on PostgreSQL and SQLite), fields= or expressions such as Lower("email"), and deferrable= on PostgreSQL.
  • CheckConstraint(condition=Q(...), name=...): in Django 5.1+ the argument is condition; the older check= argument is deprecated.
  • Index: composite indexes in query order, descending fields ("-created_at"), functional indexes (which need a name), partial indexes with condition=, and PostgreSQL-specific types (GinIndex, BrinIndex) from django.contrib.postgres.indexes.
  • Model.full_clean() validates constraints (Django 4.1+), so ModelForms and the admin show friendly errors. The database remains the final guard.
  • unique_together still works but UniqueConstraint is preferred. index_together was removed in Django 5.1.

Code/Syntax Justification:

from django.conf import settings
from django.db import models
from django.db.models import F, Q
from django.db.models.functions import Lower


class Subscription(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
plan = models.CharField(max_length=20)
is_active = models.BooleanField(default=True)
starts_at = models.DateTimeField()
ends_at = models.DateTimeField()

class Meta:
constraints = [
models.UniqueConstraint(
fields=["user"],
condition=Q(is_active=True),
name="one_active_subscription_per_user",
),
models.CheckConstraint(
condition=Q(ends_at__gt=F("starts_at")),
name="subscription_ends_after_start",
),
]
indexes = [
models.Index(fields=["user", "-starts_at"], name="sub_user_starts_idx"),
models.Index(Lower("plan"), name="sub_plan_lower_idx"),
]

🔍 Behind the Question: Whether the candidate treats the database as the source of truth for invariants, and keeps up with current Django APIs. ❌ The Red Flags: Uniqueness enforced only with if Model.objects.filter(...).exists() checks (racy); no indexes matching the hot query patterns; creating indexes on huge tables without CONCURRENTLY (see Q20).


Models, Middleware and Migrations​

Q27: Why should every new project start with a custom user model, and how do you build one?​

Technical Answer: Django's docs recommend setting AUTH_USER_MODEL to a custom model at the very start of a project, even if it's identical to the default. Swapping later is painful: every foreign key to auth.User, the existing migrations, and third-party apps all have to change together. Options:

  • AbstractUser: keeps all default fields and lets you add more. This is the usual choice.
  • AbstractBaseUser + PermissionsMixin: full control over fields, but you implement more yourself.

To log in with email instead of username on top of AbstractUser: set username = None, make email unique, set USERNAME_FIELD = "email" and REQUIRED_FIELDS = [], and provide a manager whose create_user/create_superuser don't expect a username. Reference the model with settings.AUTH_USER_MODEL in foreign keys and get_user_model() at runtime, never by importing it directly.

Code/Syntax Justification:

# accounts/models.py
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import AbstractUser
from django.db import models


class UserManager(BaseUserManager):
use_in_migrations = True

def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError("An email address is required")
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user

def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields)

def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields["is_staff"] is not True or extra_fields["is_superuser"] is not True:
raise ValueError("Superuser must have is_staff=True and is_superuser=True")
return self._create_user(email, password, **extra_fields)


class User(AbstractUser):
username = None
email = models.EmailField(unique=True)

USERNAME_FIELD = "email"
REQUIRED_FIELDS: list[str] = []

objects = UserManager()
# settings.py
AUTH_USER_MODEL = "accounts.User"

# any app's models.py
from django.conf import settings
from django.db import models


class Invoice(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)

🔍 Behind the Question: Long-term thinking about schema decisions that are expensive to change later. ❌ The Red Flags: from django.contrib.auth.models import User in app code; a separate Profile one-to-one used to work around a missing custom user model on a new project; switching AUTH_USER_MODEL after the first migration without a migration plan.


Q28: Why does middleware order matter, and what hooks can class-based middleware implement?​

Technical Answer: Requests flow top → bottom through MIDDLEWARE; responses flow bottom → top. A middleware can only use what earlier middleware has set up. Important orderings:

  • SecurityMiddleware first (HTTPS redirect, security headers). WhiteNoise, if used, goes directly after it.
  • SessionMiddleware before AuthenticationMiddleware, because authentication reads the session to set request.user.
  • CsrfViewMiddleware before any middleware that assumes CSRF has already been checked.
  • corsheaders.middleware.CorsMiddleware as high as possible, and in any case before CommonMiddleware, so CORS headers are also added to responses that other middleware short-circuits.
  • GZipMiddleware near the top, so it runs late on the response and compresses the final body.

Besides __call__, a class-based middleware can define process_view (runs just before the view, after URL resolution), process_exception (runs if the view raises), and process_template_response. Returning a response from any hook short-circuits the rest of the chain.

Code/Syntax Justification:

# settings.py
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"core.middleware.TimingMiddleware", # after auth: request.user is available
]
# core/middleware.py
import logging
import time

logger = logging.getLogger(__name__)


class TimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
start = time.perf_counter()
response = self.get_response(request)
elapsed_ms = (time.perf_counter() - start) * 1000
response["Server-Timing"] = f"app;dur={elapsed_ms:.1f}"
return response

def process_view(self, request, view_func, view_args, view_kwargs):
request.view_name = getattr(view_func, "__name__", "unknown")
return None # continue to the view

def process_exception(self, request, exception):
logger.exception(
"Unhandled error in %s for user %s",
getattr(request, "view_name", "unknown"),
getattr(request.user, "pk", None),
)
return None # let Django's normal 500 handling continue

🔍 Behind the Question: Understanding the request/response pipeline well enough to debug "why is request.user anonymous here?" and "why is the CORS header missing on 404s?" ❌ The Red Flags: Custom middleware reading request.user placed above AuthenticationMiddleware; expensive database queries in middleware on every request; swallowing exceptions in process_exception by returning a generic 200.


Q29: How do you write safe data migrations, and when do you squash migrations?​

Technical Answer: A data migration is a RunPython (or RunSQL) operation that changes rows rather than schema. Rules:

  • Use apps.get_model("app", "Model"), never a direct import. Migrations run against the historical model state; the current class may have fields that don't exist yet at that point in history. Custom model methods and managers aren't available either (unless use_in_migrations = True).
  • Always give a reverse_code (use migrations.RunPython.noop if reversing needs no action) so the migration can be rolled back.
  • Batch large updates (bulk_update in chunks ordered by pk). On PostgreSQL, set atomic = False on the migration so each batch commits separately instead of holding one huge transaction and its locks.
  • Keep schema and data changes in separate migrations.
  • Mark one-off backfills elidable=True so they are dropped when migrations are squashed.

Squashing (manage.py squashmigrations app 0001 0040) replaces a long chain with one migration that lists the old ones in replaces. Deploy it, wait until every environment has migrated past the squashed range, then delete the old files and remove replaces. manage.py optimizemigration (Django 4.1+) optimizes the operations of a single migration.

Code/Syntax Justification:

# crm/migrations/0008_backfill_full_name.py
from django.db import migrations

BATCH_SIZE = 1000


def backfill_full_name(apps, schema_editor):
Customer = apps.get_model("crm", "Customer")
while True:
batch = list(
Customer.objects.filter(full_name__isnull=True)
.order_by("pk")
.only("pk", "first_name", "last_name")[:BATCH_SIZE]
)
if not batch:
break
for customer in batch:
customer.full_name = f"{customer.first_name} {customer.last_name}".strip()
Customer.objects.bulk_update(batch, ["full_name"])


class Migration(migrations.Migration):
atomic = False # commit per batch instead of one long transaction

dependencies = [("crm", "0007_customer_full_name")]

operations = [
migrations.RunPython(
backfill_full_name,
reverse_code=migrations.RunPython.noop,
elidable=True,
),
]
python manage.py sqlmigrate crm 0008 # inspect SQL (schema migrations)
python manage.py migrate crm 0008 --plan # see what would run
python manage.py squashmigrations crm 0001 0040

🔍 Behind the Question: Production-safe data changes and migration-history hygiene in long-lived codebases. ❌ The Red Flags: Importing models from crm.models inside a migration; a single UPDATE over 50M rows inside a transaction; deleting squashed migrations before all environments have applied them.


DRF Serializers, Views and Permissions​

Q30: Serializer vs ModelSerializer — and in what order does DRF run validation?​

Technical Answer:

  • Serializer: you declare every field and implement create()/update() yourself. Use it for input that isn't a model (login, search parameters, webhook payloads).
  • ModelSerializer: generates fields from the model (types, max_length, required, choices, unique validators), plus default create()/update(). Always list fields explicitly; "__all__" leaks new columns automatically.

Validation order during is_valid():

  1. to_internal_value() runs each field's own validation (type coercion and field validators=) followed by the validate_<field_name>() method for that field.
  2. Serializer-level validators from Meta.validators (for example, UniqueTogetherValidator).
  3. validate(self, attrs) for cross-field rules.

Errors raised in validate() with a dict map to fields. Remember that Model.clean() is not called by DRF, and that during partial updates (partial=True) missing fields aren't in attrs, so fall back to self.instance.

Code/Syntax Justification:

from rest_framework import serializers

from bookings.models import Booking


class BookingSerializer(serializers.ModelSerializer):
class Meta:
model = Booking
fields = ["id", "room", "starts_at", "ends_at", "guests"]
read_only_fields = ["id"]

def validate_guests(self, value: int) -> int:
if value < 1:
raise serializers.ValidationError("At least one guest is required.")
return value

def validate(self, attrs):
# Works for create, full update and PATCH
starts_at = attrs.get("starts_at", getattr(self.instance, "starts_at", None))
ends_at = attrs.get("ends_at", getattr(self.instance, "ends_at", None))
if starts_at and ends_at and ends_at <= starts_at:
raise serializers.ValidationError({"ends_at": "Must be after starts_at."})
return attrs


class LoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField(write_only=True, trim_whitespace=False)
# view usage
serializer = BookingSerializer(data=request.data)
serializer.is_valid(raise_exception=True) # 400 with field errors on failure
booking = serializer.save(created_by=request.user) # extra kwargs go to create()

🔍 Behind the Question: Knowing where each kind of rule belongs and how partial updates interact with cross-field validation. ❌ The Red Flags: fields = "__all__" on public APIs; business validation duplicated in views; cross-field checks that crash on PATCH because a key is missing.


Q31: How do you implement writable nested serializers?​

Technical Answer: DRF's default ModelSerializer.create()/update() refuse nested writes: they raise an AssertionError telling you to write explicit .create()/.update() methods. That's deliberate, because only you know the semantics (replace the children? merge them by id? are deletes allowed?). The standard pattern:

  1. Pop the nested data out of validated_data.
  2. Create the parent, then the children (use bulk_create for efficiency), all inside transaction.atomic() so a child failure doesn't leave an orphan parent.
  3. For updates, decide the strategy explicitly. The simplest is "replace all children"; diffing by id preserves child primary keys.

Note that bulk_create skips save() and signals. For updates, consider separate endpoints for child resources instead of deep nested writes.

Code/Syntax Justification:

from django.db import transaction
from rest_framework import serializers

from shop.models import Order, OrderItem


class OrderItemSerializer(serializers.ModelSerializer):
class Meta:
model = OrderItem
fields = ["product", "quantity"]


class OrderWriteSerializer(serializers.ModelSerializer):
items = OrderItemSerializer(many=True)

class Meta:
model = Order
fields = ["id", "customer", "items"]

def validate_items(self, items):
if not items:
raise serializers.ValidationError("An order needs at least one item.")
product_ids = [item["product"].pk for item in items]
if len(product_ids) != len(set(product_ids)):
raise serializers.ValidationError("Duplicate products; adjust quantity instead.")
return items

@transaction.atomic
def create(self, validated_data):
items = validated_data.pop("items")
order = Order.objects.create(**validated_data)
OrderItem.objects.bulk_create([OrderItem(order=order, **item) for item in items])
return order

@transaction.atomic
def update(self, instance, validated_data):
items = validated_data.pop("items", None)
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()
if items is not None: # replace strategy
instance.items.all().delete()
OrderItem.objects.bulk_create([OrderItem(order=instance, **item) for item in items])
return instance

🔍 Behind the Question: Transactional thinking and explicit API semantics, not just serializer syntax. ❌ The Red Flags: Creating children one by one in a loop without a transaction; silently ignoring nested data; using one serializer for both deeply nested reads and writes when they have different shapes.


Q32: How do ViewSets and routers work, and how do you customize them per action?​

Technical Answer: A ViewSet groups the handlers for one resource (list, retrieve, create, update, partial_update, destroy). A router generates the URL patterns. Key customization points:

  • get_queryset(): scope data to the current user or tenant here. It is the main defence against data leaks, and it's where you add select_related/prefetch_related.
  • get_serializer_class(): light serializer for list, detailed one for retrieve, a separate one for writes. Branch on self.action.
  • get_permissions(): different permissions per action.
  • perform_create() / perform_update(): inject server-side values such as owner=request.user.
  • @action(detail=True/False, methods=[...]): custom endpoints such as /projects/{pk}/archive/.

When the ViewSet has no queryset class attribute (because you override get_queryset()), you must pass basename to router.register().

Code/Syntax Justification:

# projects/views.py
from rest_framework import permissions, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

from projects.models import Project
from projects.serializers import ProjectDetailSerializer, ProjectListSerializer


class ProjectViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated]

def get_queryset(self):
return (
Project.objects.filter(organization__members=self.request.user)
.select_related("owner", "organization")
.order_by("-created_at")
)

def get_serializer_class(self):
if self.action == "list":
return ProjectListSerializer
return ProjectDetailSerializer

def get_permissions(self):
if self.action == "destroy":
return [permissions.IsAdminUser()]
return super().get_permissions()

def perform_create(self, serializer):
serializer.save(owner=self.request.user)

@action(detail=True, methods=["post"])
def archive(self, request, pk=None):
project = self.get_object() # runs object-level permission checks
project.is_archived = True
project.save(update_fields=["is_archived"])
return Response(status=status.HTTP_204_NO_CONTENT)
# projects/urls.py
from rest_framework.routers import DefaultRouter

from projects.views import ProjectViewSet

router = DefaultRouter()
router.register("projects", ProjectViewSet, basename="project")
urlpatterns = router.urls
# /projects/ /projects/{pk}/ /projects/{pk}/archive/

🔍 Behind the Question: Whether the candidate uses the right extension hooks instead of overriding whole handlers, and scopes data in get_queryset(). ❌ The Red Flags: queryset = Project.objects.all() with no per-user scoping; overriding list() just to change the serializer; custom actions that fetch objects directly instead of calling get_object(), which skips permission checks.


Q33: How do DRF permissions work — has_permission vs has_object_permission?​

Technical Answer:

  • has_permission(request, view) runs for every request, before the handler. Use it for view-level rules (authenticated? has a role? plan allows this endpoint?).
  • has_object_permission(request, view, obj) runs only when self.get_object() is called, which means retrieve/update/destroy and custom detail actions that call it. It is never called for list, so list endpoints must be protected by filtering in get_queryset().
  • Permissions combine with &, | and ~ (for example, IsAuthenticated & (IsOwner | IsAdminUser)).
  • If a custom view fetches objects itself, call self.check_object_permissions(request, obj) explicitly.
  • Filtering in get_queryset() makes other users' objects return 404, which hides their existence. An object permission failure returns 403.

Code/Syntax Justification:

from rest_framework import permissions, viewsets

from docs.models import Document
from docs.serializers import DocumentSerializer


class IsOwnerOrReadOnly(permissions.BasePermission):
message = "Only the owner can modify this document."

def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner_id == request.user.id


class IsPaidPlan(permissions.BasePermission):
def has_permission(self, request, view):
return bool(request.user and request.user.is_authenticated and request.user.plan != "free")


class DocumentViewSet(viewsets.ModelViewSet):
serializer_class = DocumentSerializer
permission_classes = [permissions.IsAuthenticated & (IsOwnerOrReadOnly | permissions.IsAdminUser)]

def get_queryset(self):
# Protects LIST: object permissions are never evaluated there
return Document.objects.filter(workspace__members=self.request.user)

def get_permissions(self):
if self.action == "export":
return [IsPaidPlan()]
return super().get_permissions()

🔍 Behind the Question: Authorization correctness. Confusing these two hooks is a common cause of IDOR (insecure direct object reference) bugs. ❌ The Red Flags: Relying on has_object_permission to protect list endpoints; permission logic duplicated inside handlers; AllowAny set globally "for now."


DRF API Design: Pagination, Auth, Filtering, Versioning​

Q34: What are the trade-offs between DRF's pagination styles?​

Technical Answer:

  • PageNumberPagination (?page=3): familiar and supports "jump to page N", but runs COUNT(*) on every request and uses OFFSET, which gets slower the deeper you go. Rows shift when data is inserted between requests, causing duplicates or skipped rows.
  • LimitOffsetPagination (?limit=50&offset=100): same costs as page numbers, but gives the client more control.
  • CursorPagination (opaque ?cursor=...): seeks by an indexed ordering column. There's no COUNT, cost stays constant at any depth, and results are stable under concurrent inserts. You can't jump to an arbitrary page, and it needs a fixed, (nearly) unique, indexed ordering. Best for feeds, infinite scroll, sync APIs and very large tables.

Always cap the page size (max_page_size) so clients can't request a million rows.

Code/Syntax Justification:

# settings.py
REST_FRAMEWORK = {
"DEFAULT_PAGINATION_CLASS": "core.pagination.StandardPagination",
"PAGE_SIZE": 50,
}
# core/pagination.py
from rest_framework.pagination import CursorPagination, PageNumberPagination


class StandardPagination(PageNumberPagination):
page_size = 50
page_size_query_param = "page_size"
max_page_size = 200


class FeedCursorPagination(CursorPagination):
page_size = 100
ordering = ("-created_at", "-id") # back it with a matching composite index
# views.py
from rest_framework import generics

from core.pagination import FeedCursorPagination
from feed.models import Event
from feed.serializers import EventSerializer


class EventFeed(generics.ListAPIView):
serializer_class = EventSerializer
pagination_class = FeedCursorPagination

def get_queryset(self):
return Event.objects.filter(account=self.request.user.account)

🔍 Behind the Question: Understanding the database cost behind each API style, especially at scale. ❌ The Red Flags: Unbounded list endpoints; offset pagination on a 100M-row table; cursor pagination ordered by a non-indexed or frequently changing field.


Q35: Session vs Token vs JWT authentication in DRF — when do you use which?​

Technical Answer:

  • SessionAuthentication: a cookie-based Django session. Best for a first-party browser SPA on the same site. DRF enforces CSRF for authenticated unsafe requests (POST/PUT/PATCH/DELETE), so the frontend must send the CSRF token. Revocation is immediate (delete the session).
  • TokenAuthentication (rest_framework.authtoken): one opaque token per user, stored in the database and sent as Authorization: Token <key>. Simple, and revocable by deleting the row. It has no built-in expiry, and each request costs a database lookup.
  • JWT (djangorestframework-simplejwt): signed, stateless access tokens plus refresh tokens. No database lookup per request and works across services. Revocation is hard, so keep access tokens short-lived, rotate refresh tokens, and enable the blacklist app for logout. Never put secrets in the payload; it's only base64-encoded, not encrypted.
  • The first class in DEFAULT_AUTHENTICATION_CLASSES determines the WWW-Authenticate header, and therefore whether unauthenticated requests get 401 or 403.

Code/Syntax Justification:

# settings.py
from datetime import timedelta

INSTALLED_APPS = [
# ...
"rest_framework",
"rest_framework_simplejwt.token_blacklist",
]

REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework_simplejwt.authentication.JWTAuthentication", # API clients
"rest_framework.authentication.SessionAuthentication", # browsable API / admin users
],
"DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
}

SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=5),
"REFRESH_TOKEN_LIFETIME": timedelta(days=7),
"ROTATE_REFRESH_TOKENS": True,
"BLACKLIST_AFTER_ROTATION": True,
}
# urls.py
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
path("api/auth/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"),
path("api/auth/token/refresh/", TokenRefreshView.as_view(), name="token_refresh"),
]

🔍 Behind the Question: Choosing auth based on clients, revocation needs and threat model, not hype. ❌ The Red Flags: JWTs valid for 30 days with no revocation; storing JWTs in localStorage without considering XSS; disabling CSRF to "make session auth work."


Q36: How do you implement filtering, search and ordering in DRF?​

Technical Answer:

  • django-filter (DjangoFilterBackend + FilterSet): typed, validated query parameters (?min_price=10&category=books). Invalid values give a 400 instead of a 500.
  • SearchFilter (?search=term): icontains across search_fields by default. Prefixes change the lookup: ^ starts-with, = exact, @ full-text search (PostgreSQL), $ regex.
  • OrderingFilter (?ordering=-price): always whitelist ordering_fields, so clients can't sort on unindexed or sensitive columns, and set a default ordering for stable pagination.

Performance: icontains becomes LIKE '%term%', which can't use a B-tree index. At scale, use PostgreSQL full-text search, trigram indexes (pg_trgm), or a search engine.

Code/Syntax Justification:

# catalog/filters.py
import django_filters

from catalog.models import Product


class ProductFilter(django_filters.FilterSet):
min_price = django_filters.NumberFilter(field_name="price", lookup_expr="gte")
max_price = django_filters.NumberFilter(field_name="price", lookup_expr="lte")
category = django_filters.CharFilter(field_name="category__slug")

class Meta:
model = Product
fields = ["in_stock"]
# catalog/views.py
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, viewsets

from catalog.filters import ProductFilter
from catalog.models import Product
from catalog.serializers import ProductSerializer


class ProductViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Product.objects.select_related("category")
serializer_class = ProductSerializer
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filterset_class = ProductFilter
search_fields = ["name", "^sku"]
ordering_fields = ["price", "created_at"]
ordering = ["-created_at"]

# GET /products/?category=books&min_price=10&search=django&ordering=price

🔍 Behind the Question: Building flexible list APIs without hand-parsing query strings or opening performance and security holes. ❌ The Red Flags: Parsing request.query_params manually with no validation; unrestricted ordering on any field; icontains search on a huge table with no index strategy.


Q37: How do you version a DRF API?​

Technical Answer: DRF's built-in versioning schemes set request.version:

  • URLPathVersioning (/api/v1/orders/): explicit, easy to route, cache and debug. The most common choice.
  • NamespaceVersioning: the version comes from the URL namespace.
  • AcceptHeaderVersioning (Accept: application/json; version=2): clean URLs, but harder to test in a browser and needs careful Vary handling for caches.
  • QueryParameterVersioning / HostNameVersioning: less common.

Configure ALLOWED_VERSIONS so unknown versions are rejected. Branch on request.version in get_serializer_class() rather than duplicating whole views. Version only on breaking changes; additive fields don't need a new version. Announce deprecations (for example with a Sunset header, RFC 8594) and monitor traffic per version before removing one.

Code/Syntax Justification:

# settings.py
REST_FRAMEWORK = {
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning",
"DEFAULT_VERSION": "v1",
"ALLOWED_VERSIONS": ["v1", "v2"],
}
# urls.py
from django.urls import include, path

urlpatterns = [
path("api/<str:version>/", include("orders.urls")),
]
# orders/views.py
from rest_framework import viewsets

from orders.models import Order
from orders.serializers import OrderSerializerV1, OrderSerializerV2


class OrderViewSet(viewsets.ReadOnlyModelViewSet):
def get_queryset(self):
return Order.objects.filter(customer__user=self.request.user)

def get_serializer_class(self):
if self.request.version == "v1":
return OrderSerializerV1 # legacy shape: "total" as a string
return OrderSerializerV2

def finalize_response(self, request, response, *args, **kwargs):
response = super().finalize_response(request, response, *args, **kwargs)
if request.version == "v1":
response["Sunset"] = "Wed, 30 Jun 2027 23:59:59 GMT"
return response

🔍 Behind the Question: API evolution without breaking existing clients (mobile apps can't be force-upgraded). ❌ The Red Flags: Breaking response shapes in place; a new version for every additive change; copy-pasted v1/v2 view modules that drift apart.


Async, Testing and Security Settings​

Q38: How do async views work in Django, and what are the limitations?​

Technical Answer: Django supports async def views, async middleware and an async ORM interface. Async pays off when a view waits on several I/O operations concurrently, for example multiple HTTP calls fanned out with asyncio.gather, or long-lived connections.

  • Run under ASGI (uvicorn, daphne, hypercorn) to get the benefit. Under WSGI an async view still works, but Django runs it in a one-off event loop per request, so you gain nothing.
  • Async ORM: aget(), acreate(), acount(), aexists(), async for obj in queryset, and await request.auser() (Django 5.0+). Database queries still run in a thread pool under the hood, so the async ORM helps concurrency but doesn't make queries faster.
  • Transactions don't work in async code yet. Put transactional work in a sync function and call it with sync_to_async.
  • Any synchronous middleware in the stack forces a sync/async context switch on every request, costing performance. Check that your middleware is async-capable.
  • DRF's APIView is synchronous. Plain Django async views (or third-party packages) are needed for async API endpoints.

Code/Syntax Justification:

# dashboard/views.py
import asyncio

import httpx
from asgiref.sync import sync_to_async
from django.db import transaction
from django.http import JsonResponse

from shop.models import Order


async def dashboard(request):
user = await request.auser()
async with httpx.AsyncClient(timeout=5) as client:
weather_resp, rates_resp = await asyncio.gather(
client.get("https://weather.example.com/api/today"),
client.get("https://rates.example.com/api/latest"),
)
open_orders = await Order.objects.filter(customer__user=user, status="open").acount()
recent = [
row
async for row in Order.objects.filter(customer__user=user)
.order_by("-created_at")
.values("id", "total")[:5]
]
return JsonResponse(
{
"weather": weather_resp.json(),
"rates": rates_resp.json(),
"open_orders": open_orders,
"recent": recent,
}
)


def _close_order(order_id: int) -> None:
with transaction.atomic():
order = Order.objects.select_for_update().get(pk=order_id)
order.status = "closed"
order.save(update_fields=["status"])


async def close_order(request, order_id: int):
await sync_to_async(_close_order)(order_id) # transactions must run in sync code
return JsonResponse({"status": "closed"})

🔍 Behind the Question: Knowing when async helps (concurrent I/O) and the sharp edges (transactions, sync middleware, DRF). ❌ The Red Flags: Converting CPU-bound or single-query views to async "for speed"; calling sync ORM methods directly in an async view (raises SynchronousOnlyOperation); deploying async views on WSGI and expecting gains.


Q39: How do you test DRF APIs and lock in query counts?​

Technical Answer:

  • Use APIClient (or APITestCase) with force_authenticate(user=...) to skip the authentication machinery when it isn't what you're testing.
  • With pytest-django: @pytest.mark.django_db for database access (each test runs inside a rolled-back transaction), and the fixtures django_assert_num_queries / django_assert_max_num_queries. With unittest-style tests, use self.assertNumQueries(n).
  • The most robust N+1 guard checks that the query count doesn't grow with the number of rows: capture queries for 5 rows and for 50 rows and assert the counts are equal.
  • Test on the real database engine you use in production (PostgreSQL), and include permission tests: another user's object must return 404/403.

Code/Syntax Justification:

# tests/test_orders_api.py
import pytest
from django.db import connection
from django.test.utils import CaptureQueriesContext
from rest_framework.test import APIClient

from tests.factories import OrderFactory, UserFactory


@pytest.fixture
def user():
return UserFactory()


@pytest.fixture
def api_client(user):
client = APIClient()
client.force_authenticate(user=user)
return client


def count_queries(client: APIClient, url: str) -> int:
with CaptureQueriesContext(connection) as ctx:
response = client.get(url)
assert response.status_code == 200
return len(ctx.captured_queries)


@pytest.mark.django_db
def test_order_list_has_no_n_plus_one(api_client, user):
OrderFactory.create_batch(5, customer__user=user) # rows the endpoint will return
small = count_queries(api_client, "/api/orders/")
OrderFactory.create_batch(45, customer__user=user)
large = count_queries(api_client, "/api/orders/")
assert small == large # constant number of queries regardless of row count


@pytest.mark.django_db
def test_order_detail_query_budget(api_client, user, django_assert_max_num_queries):
order = OrderFactory(customer__user=user)
with django_assert_max_num_queries(4):
api_client.get(f"/api/orders/{order.pk}/")


@pytest.mark.django_db
def test_cannot_read_someone_elses_order(api_client):
other_order = OrderFactory() # belongs to a different user
response = api_client.get(f"/api/orders/{other_order.pk}/")
assert response.status_code == 404

🔍 Behind the Question: Turning performance and authorization expectations into regression tests, instead of hoping code review catches them. ❌ The Red Flags: Only testing the happy path with an admin user; no query-count assertions on list endpoints; testing on SQLite while production runs PostgreSQL.


Q40: Which security settings must be set for a production Django deployment?​

Technical Answer: Start with python manage.py check --deploy, which flags missing or weak settings. The essentials:

  • DEBUG = False, a strong SECRET_KEY from the environment, and an explicit ALLOWED_HOSTS.
  • HTTPS: SECURE_SSL_REDIRECT = True; SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE. If TLS terminates at a proxy, set SECURE_PROXY_SSL_HEADER, but only if the proxy always sets or overwrites that header; otherwise clients can spoof HTTPS.
  • HSTS: SECURE_HSTS_SECONDS (start small, e.g. 3600, then raise to a year), SECURE_HSTS_INCLUDE_SUBDOMAINS, and SECURE_HSTS_PRELOAD only once you're sure every subdomain serves HTTPS.
  • CSRF_TRUSTED_ORIGINS for cross-origin forms or SPAs (scheme required, e.g. https://app.example.com).
  • Defaults worth knowing: SECURE_CONTENT_TYPE_NOSNIFF = True, X_FRAME_OPTIONS = "DENY", SECURE_REFERRER_POLICY = "same-origin", SESSION_COOKIE_HTTPONLY = True.
  • For CORS, list explicit origins with django-cors-headers; never allow all origins together with credentials.

Keep per-environment settings in modules (settings/base.py, settings/production.py) selected by DJANGO_SETTINGS_MODULE, with secrets read from environment variables or a secrets manager.

Code/Syntax Justification:

# config/settings/production.py
import os

from .base import * # noqa: F403

DEBUG = False
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
ALLOWED_HOSTS = ["api.example.com"]
CSRF_TRUSTED_ORIGINS = ["https://app.example.com"]

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # only behind a trusted proxy
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

SECURE_HSTS_SECONDS = 31_536_000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

CORS_ALLOWED_ORIGINS = ["https://app.example.com"]
CORS_ALLOW_CREDENTIALS = True
DJANGO_SETTINGS_MODULE=config.settings.production python manage.py check --deploy

🔍 Behind the Question: Practical security hygiene and an understanding of what each header protects against. ❌ The Red Flags: ALLOWED_HOSTS = ["*"]; CORS_ALLOW_ALL_ORIGINS = True with credentials; jumping straight to a one-year HSTS preload without verifying subdomains; trusting X-Forwarded-Proto from clients.


Senior / Principal — Production Django Scenarios​

Q41: SerializerMethodField turns a list endpoint into thousands of queries​

Level: Senior

Scenario: /api/projects/ returns 200 projects per page. Someone added open_task_count and last_activity_at as SerializerMethodFields, plus owner_name via source="owner.get_full_name". select_related is already on the view, yet p95 latency went from 120 ms to 4 s and the database shows about 600 queries per request.

Impact: Slow dashboards, database CPU saturation at peak, and timeouts on mobile.

Root Cause: Each get_<field> method runs its own query per row (obj.tasks.filter(...).count(), obj.activities.order_by(...).first()). Prefetching doesn't help, because .filter()/.order_by() on a related manager bypasses prefetched data. Together with an owner relation that wasn't actually in select_related, that's 1 + 3 × 200 queries.

Fix:

  1. Move per-row computations into the queryset with annotate(): a Subquery count for open tasks (avoids join multiplication) and Max() for the last activity.
  2. Replace SerializerMethodFields with plain read-only fields that read the annotations.
  3. Add select_related("owner") for the FK traversal.
  4. Lock it in with a test that asserts a constant number of queries (see Q39).

Code/Syntax Justification:

# BEFORE (one query per row per method)
from rest_framework import serializers

from projects.models import Project


class ProjectSerializerSlow(serializers.ModelSerializer):
open_task_count = serializers.SerializerMethodField()
last_activity_at = serializers.SerializerMethodField()
owner_name = serializers.CharField(source="owner.get_full_name", read_only=True)

class Meta:
model = Project
fields = ["id", "name", "owner_name", "open_task_count", "last_activity_at"]

def get_open_task_count(self, obj):
return obj.tasks.filter(status="open").count()

def get_last_activity_at(self, obj):
latest = obj.activities.order_by("-created_at").first()
return latest.created_at if latest else None
# AFTER: everything computed in SQL
from django.db.models import Count, Max, OuterRef, Subquery
from django.db.models.functions import Coalesce
from rest_framework import serializers, viewsets

from projects.models import Project, Task


class ProjectSerializer(serializers.ModelSerializer):
open_task_count = serializers.IntegerField(read_only=True)
last_activity_at = serializers.DateTimeField(read_only=True, allow_null=True)
owner_name = serializers.CharField(source="owner.get_full_name", read_only=True)

class Meta:
model = Project
fields = ["id", "name", "owner_name", "open_task_count", "last_activity_at"]


class ProjectViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = ProjectSerializer

def get_queryset(self):
open_tasks = (
Task.objects.filter(project=OuterRef("pk"), status="open")
.order_by() # clear Meta.ordering so GROUP BY is only on project
.values("project")
.annotate(c=Count("pk"))
.values("c")
)
return (
Project.objects.filter(organization__members=self.request.user)
.select_related("owner")
.annotate(
open_task_count=Coalesce(Subquery(open_tasks), 0),
last_activity_at=Max("activities__created_at"),
)
.order_by("-id")
)

Workflow Diagram:

BEFORE (200 rows):
1 query projects
200 tasks.filter(status=open).count()
200 activities.order_by().first()
200 owner lookup
~601 queries, 4 s

AFTER:
1 query projects
JOIN owner (select_related)
+ correlated subquery for count (annotate)
+ MAX(activities.created_at) (annotate)
(+1 COUNT for pagination)
2 queries, ~100 ms

🔍 Interviewer Notes: Strong candidates recognize that SerializerMethodField plus ORM calls is a hidden N+1, explain why prefetching doesn't help when you filter the related manager, and know the join-multiplication trap when annotating over two relations.

❌ Red Flags: Adding a cache layer in front of the endpoint instead of fixing the queries; raising the page size limit to "reduce requests"; no regression test on query count.


Q42: A management command exhausts memory iterating a huge QuerySet​

Level: Senior

Scenario: A nightly export_orders command writes 20 million paid orders to CSV. It worked at 1 million rows. Now the pod is OOM-killed after 25 minutes, and the export silently never reaches the finance team.

Impact: Missing financial exports, repeated OOM kills that affect co-located workloads, and manual re-runs.

Root Cause: for order in Order.objects.filter(...) evaluates the QuerySet and stores every model instance in the result cache, and the code then touches order.customer.email (one extra query per row). If the command runs with DEBUG=True, Django also records every SQL query in connection.queries. Memory grows linearly with the table.

Fix:

  1. Stream with keyset batching by primary key (pk__gt=last_pk ... [:batch]). Each batch is a short, index-friendly query, there's no long-lived transaction, and it works behind PgBouncer.
  2. Fetch tuples with values_list(...), including related columns via __ lookups (a JOIN instead of a query per row). No model instances are built at all.
  3. Alternatively use .iterator(chunk_size=...) when a single long-running cursor is acceptable.
  4. Make sure DEBUG=False in job environments and stream output to a file or object storage instead of building it in memory.

Code/Syntax Justification:

# shop/management/commands/export_orders.py
import csv

from django.core.management.base import BaseCommand

from shop.models import Order


class Command(BaseCommand):
help = "Export paid orders to CSV with constant memory usage"

def add_arguments(self, parser):
parser.add_argument("path")
parser.add_argument("--batch-size", type=int, default=5000)

def handle(self, *args, path, batch_size, **options):
last_pk = 0
written = 0
with open(path, "w", newline="") as fh:
writer = csv.writer(fh)
writer.writerow(["id", "customer_email", "total", "created_at"])
while True:
rows = list(
Order.objects.filter(status="paid", pk__gt=last_pk)
.order_by("pk")
.values_list("pk", "customer__email", "total", "created_at")[:batch_size]
)
if not rows:
break
writer.writerows(rows)
last_pk = rows[-1][0]
written += len(rows)
self.stdout.write(self.style.SUCCESS(f"Exported {written} orders to {path}"))

Workflow Diagram:

BEFORE:
SELECT * FROM orders WHERE status='paid' (20M rows)
-> 20M model instances in _result_cache (memory grows until OOM)
-> + 20M "SELECT customer" queries

AFTER (per batch of 5,000):
SELECT id, customer.email, total, created_at
FROM orders JOIN customer
WHERE status='paid' AND id > :last_pk
ORDER BY id LIMIT 5000
-> write rows -> discard -> next batch
Memory: flat (one batch of tuples)

🔍 Interviewer Notes: Look for the difference between iterator() and keyset pagination (long cursor vs short independent queries), awareness of DEBUG query logging, and avoiding model instances when you only need columns.

❌ Red Flags: "Give the pod more memory"; Paginator with OFFSET over 20M rows (it gets slower with every page); list(Model.objects.all()) in batch jobs.


Q43: Celery task runs before the transaction commits — DoesNotExist in workers​

Level: Senior

Scenario: After an order is created, a Celery task sends the confirmation email. About 2% of tasks fail with Order.DoesNotExist, and a few emails show stale data. The failures increase when the database is under load. Locally everything works.

Impact: Customers get no confirmation, support tickets increase, and retries hide the problem in some cases but not others.

Root Cause: send_confirmation.delay(order.pk) is called inside a transaction (explicit atomic() or ATOMIC_REQUESTS = True). The message reaches the broker immediately, and a fast worker reads the database before the web request's transaction commits, so the row isn't visible yet. If the transaction later rolls back, the task runs for an order that never existed.

Fix:

  1. Enqueue with transaction.on_commit() so the task is published only after a successful commit, and never on rollback. (Celery 5.4+ also offers delay_on_commit() on tasks that use its Django task class.)
  2. Pass IDs, not model instances, and have the task re-read fresh state.
  3. Make tasks idempotent (check whether the email was already sent) and retry on transient errors.
  4. For guaranteed delivery (the process can crash between commit and publish), use the transactional outbox pattern: write an outbox row in the same transaction and relay it to the broker separately.
  5. In tests, on_commit callbacks don't fire inside TestCase transactions. Use self.captureOnCommitCallbacks(execute=True) or pytest-django's django_capture_on_commit_callbacks.

Code/Syntax Justification:

# orders/services.py
from functools import partial

from django.db import transaction

from orders.models import Order
from orders.tasks import send_confirmation


def place_order(customer_id: int, total) -> Order:
with transaction.atomic():
order = Order.objects.create(customer_id=customer_id, total=total, status="placed")
# BAD: send_confirmation.delay(order.pk) -> worker may read before COMMIT
transaction.on_commit(partial(send_confirmation.delay, order.pk))
return order
# orders/tasks.py
from smtplib import SMTPException

from celery import shared_task
from django.core.mail import send_mail
from django.utils import timezone

from orders.models import Order


@shared_task(bind=True, max_retries=5, default_retry_delay=10)
def send_confirmation(self, order_id: int) -> None:
# Atomically claim the send so concurrent or retried runs don't email twice
claimed = Order.objects.filter(pk=order_id, confirmation_sent_at__isnull=True).update(
confirmation_sent_at=timezone.now()
)
if not claimed:
return # idempotent: already sent (or being sent)
order = Order.objects.select_related("customer").get(pk=order_id)
try:
send_mail(
subject=f"Order #{order.pk} confirmed",
message="Thanks for your order!",
from_email=None,
recipient_list=[order.customer.email],
)
except SMTPException as exc:
Order.objects.filter(pk=order_id).update(confirmation_sent_at=None) # release the claim
raise self.retry(exc=exc)
# tests/test_place_order.py
from unittest.mock import patch

import pytest

from orders.services import place_order
from orders.tasks import send_confirmation
from tests.factories import CustomerFactory


@pytest.mark.django_db
def test_task_enqueued_only_after_commit(django_capture_on_commit_callbacks):
customer = CustomerFactory()
with patch.object(send_confirmation, "delay") as delay:
with django_capture_on_commit_callbacks(execute=True) as callbacks:
order = place_order(customer.pk, total=100)
delay.assert_not_called() # nothing published while the transaction is open
assert len(callbacks) == 1
delay.assert_called_once_with(order.pk)

Workflow Diagram:

BAD:
web: BEGIN -> INSERT order -> publish task -> ... -> COMMIT
worker: SELECT order (not visible yet) -> DoesNotExist

GOOD:
web: BEGIN -> INSERT order -> register on_commit -> COMMIT -> publish task
worker: SELECT order (visible)
rollback path: on_commit callback discarded -> no task

🔍 Interviewer Notes: Senior candidates spot that ATOMIC_REQUESTS makes every view transactional, so the bug hides in innocent-looking code. Principal candidates bring up the outbox pattern for the crash window between commit and publish.

❌ Red Flags: "Add countdown=5 to the task" (a race with a longer fuse); passing pickled model instances to tasks; non-idempotent email or payment tasks with automatic retries.


Q44: Lost updates on a wallet balance under concurrent requests​

Level: Principal

Scenario: A fintech app shows users a wallet balance. Two simultaneous purchases (mobile app plus web) each read balance = 100, each subtract 80 in Python, and each save. The final balance is 20 instead of rejecting the second purchase, and the ledger shows two debits. Separately, two support agents editing the same customer record overwrite each other's changes without noticing.

Impact: Money created out of thin air, reconciliation failures, regulatory exposure, and silently lost edits.

Root Cause: Read-modify-write in application code (wallet.balance -= amount; wallet.save()) with no concurrency control. The last writer wins. save() writes every field by default, so it also overwrites concurrent changes to unrelated fields.

Fix:

  1. Conditional atomic UPDATE for counters and balances: filter(pk=..., balance__gte=amount).update(balance=F("balance") - amount). The database checks and applies the change in one statement, and the returned row count tells you whether it succeeded.
  2. Record a ledger entry in the same transaction, so the balance and its history can't diverge.
  3. Add a CheckConstraint(balance >= 0) as the final safety net.
  4. For multi-field edits by humans, use optimistic locking: a version column checked in the UPDATE ... WHERE version = :seen. Return 409 Conflict (or 412 with If-Match/ETag) when it changed.
  5. Use select_for_update() (pessimistic locking) when you must read, decide in Python, and write under contention. Keep those transactions short.

Code/Syntax Justification:

# wallets/models.py
from django.conf import settings
from django.db import models
from django.db.models import Q


class Wallet(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
balance = models.DecimalField(max_digits=12, decimal_places=2)

class Meta:
constraints = [
models.CheckConstraint(condition=Q(balance__gte=0), name="wallet_balance_non_negative"),
]


class LedgerEntry(models.Model):
wallet = models.ForeignKey(Wallet, on_delete=models.PROTECT, related_name="entries")
amount = models.DecimalField(max_digits=12, decimal_places=2) # negative = debit
reference = models.CharField(max_length=64, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
# wallets/services.py
from decimal import Decimal

from django.db import transaction
from django.db.models import F

from wallets.models import LedgerEntry, Wallet


class InsufficientFunds(Exception):
pass


def debit(wallet_id: int, amount: Decimal, reference: str) -> None:
with transaction.atomic():
updated = Wallet.objects.filter(pk=wallet_id, balance__gte=amount).update(
balance=F("balance") - amount
)
if updated == 0:
raise InsufficientFunds(wallet_id)
LedgerEntry.objects.create(wallet_id=wallet_id, amount=-amount, reference=reference)
# Optimistic locking for human edits
from django.db.models import F
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from crm.models import CustomerProfile


@api_view(["PATCH"])
def update_profile(request, pk: int) -> Response:
seen_version = int(request.data["version"])
updated = CustomerProfile.objects.filter(pk=pk, version=seen_version).update(
notes=request.data["notes"],
version=F("version") + 1,
)
if updated == 0:
return Response({"detail": "Record changed by someone else; reload."}, status=status.HTTP_409_CONFLICT)
return Response({"version": seen_version + 1})

Workflow Diagram:

LOST UPDATE:
A: read 100 B: read 100
A: write 20 B: write 20 -> two debits, balance 20 (should be rejected)

CONDITIONAL UPDATE:
A: UPDATE ... SET balance=balance-80 WHERE id=1 AND balance>=80 -> 1 row (100 -> 20)
B: UPDATE ... SET balance=balance-80 WHERE id=1 AND balance>=80 -> 0 rows -> InsufficientFunds
(B waits on A's row lock, then re-checks the condition against the committed value)

🔍 Interviewer Notes: Principal candidates compare pessimistic and optimistic locking and conditional updates, choose based on contention and UX, and insist on a ledger plus a database constraint. Ask what happens under REPEATABLE READ versus READ COMMITTED.

❌ Red Flags: wallet.balance -= x; wallet.save(); checking the balance in Python and then updating in a separate statement; "we'll reconcile it in a nightly job."


Q45: Removing a column breaks running pods during a rolling deploy​

Level: Principal

Scenario: A release removes the unused legacy_code field from Order. The pipeline runs migrate and then rolls out new pods gradually. For about four minutes, the old pods still serving traffic throw ProgrammingError: column "legacy_code" does not exist on every order query. Checkout error rates spike.

Impact: A partial outage during every deploy that touches the schema. Teams start scheduling "maintenance windows" for routine changes.

Root Cause: Django selects every model column explicitly (SELECT id, ..., legacy_code FROM ...). During a rolling deploy, old and new code run against the same schema at the same time. Dropping (or renaming) a column that the old code still references breaks the old pods. The reverse ordering breaks too: if the column is NOT NULL without a database default, new code that no longer sets it will fail on INSERT.

Fix (expand/contract over several releases):

  1. Release N: make the column safe to ignore: null=True (or add a database default with db_default, Django 5.0+). Stop reading and writing it in code.
  2. Release N+1: remove the field from the model using SeparateDatabaseAndState, so Django's state forgets the column but the database keeps it. Old pods still work, and new pods no longer select it.
  3. Release N+2: drop the column with RunSQL, with a short lock_timeout so a blocked ALTER fails fast instead of queuing behind long transactions and blocking all traffic.
  4. Renames follow the same pattern: add the new column, dual-write, backfill, switch reads, stop writing the old one, drop it later. Never use RenameField on a hot table during a rolling deploy.
  5. Add a CI check that flags dangerous operations (drops, renames, non-concurrent indexes) in new migrations, and review sqlmigrate output.

Code/Syntax Justification:

# Release N: shop/migrations/0042_order_legacy_code_nullable.py
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [("shop", "0041_previous")]

operations = [
migrations.AlterField(
model_name="order",
name="legacy_code",
field=models.CharField(max_length=32, null=True, blank=True),
),
]
# Release N+1: shop/migrations/0043_remove_order_legacy_code_state.py
from django.db import migrations


class Migration(migrations.Migration):
dependencies = [("shop", "0042_order_legacy_code_nullable")]

operations = [
migrations.SeparateDatabaseAndState(
state_operations=[migrations.RemoveField(model_name="order", name="legacy_code")],
database_operations=[], # column stays in the DB for now
),
]
# Release N+2: shop/migrations/0044_drop_order_legacy_code.py
from django.db import migrations


class Migration(migrations.Migration):
dependencies = [("shop", "0043_remove_order_legacy_code_state")]

operations = [
migrations.RunSQL(
sql=[
"SET LOCAL lock_timeout = '5s';",
"ALTER TABLE shop_order DROP COLUMN IF EXISTS legacy_code;",
],
reverse_sql=migrations.RunSQL.noop,
),
]

Workflow Diagram:

Release N : column nullable, code stops using it old pods OK / new pods OK
Release N+1 : model forgets column (state only) old pods OK / new pods OK
Release N+2 : DROP COLUMN (lock_timeout 5s) nothing references it

Unsafe single-step:
migrate (DROP) ---> old pods: SELECT ... legacy_code ---> ProgrammingError

🔍 Interviewer Notes: A principal answer reasons about two code versions running against one schema at the same time. Look for SeparateDatabaseAndState, lock_timeout, and the NOT NULL insert trap.

❌ Red Flags: RemoveField/RenameField and deploy in one release; "just run migrations after the rollout"; no lock timeout on DDL against hot tables.


Q46: Duplicate records from double-submits and webhook retries​

Level: Senior

Scenario: The payment provider retries webhooks if it doesn't get a 2xx response within 10 seconds. During a slow period, the same payment.succeeded event is processed three times. Customers are credited three times, and some users double-clicking "Subscribe" end up with two active subscriptions.

Impact: Financial loss, corrupted subscription state, and manual cleanup.

Root Cause: The "check then insert" logic (if not exists(): create()) is racy. Two requests both pass the check before either inserts. There is no unique constraint on the natural key (provider + event ID, or user + active subscription), so the database can't reject the duplicate. A naive fix that catches IntegrityError inside an atomic() block without a savepoint then breaks the transaction (TransactionManagementError).

Fix:

  1. Add a unique constraint on the idempotency key (provider + event_id) and a conditional UniqueConstraint for "one active subscription per user."
  2. Insert the idempotency record first, in the same transaction as the side effect. If the insert fails with IntegrityError, it's a duplicate: return 200 without doing anything.
  3. Wrap the insert in a nested atomic() (savepoint), so catching IntegrityError doesn't break the outer transaction.
  4. For client requests, accept an Idempotency-Key header and store it the same way.
  5. get_or_create() is safe under concurrency only if a unique constraint covers the lookup fields. It catches the IntegrityError and re-fetches the row.

Code/Syntax Justification:

# payments/models.py
from django.db import models


class WebhookEvent(models.Model):
provider = models.CharField(max_length=30)
event_id = models.CharField(max_length=255)
received_at = models.DateTimeField(auto_now_add=True)

class Meta:
constraints = [
models.UniqueConstraint(fields=["provider", "event_id"], name="uniq_webhook_event"),
]


class Credit(models.Model):
account_id = models.BigIntegerField()
amount = models.DecimalField(max_digits=12, decimal_places=2)
source_event = models.OneToOneField(WebhookEvent, on_delete=models.PROTECT)
# payments/services.py
from decimal import Decimal

from django.db import IntegrityError, transaction

from payments.models import Credit, WebhookEvent


def handle_payment_succeeded(provider: str, event_id: str, account_id: int, amount: str) -> bool:
"""Returns True if processed, False if it was a duplicate delivery."""
with transaction.atomic():
try:
with transaction.atomic(): # savepoint: an IntegrityError here won't poison the outer block
event = WebhookEvent.objects.create(provider=provider, event_id=event_id)
except IntegrityError:
return False # already processed
Credit.objects.create(account_id=account_id, amount=Decimal(amount), source_event=event)
return True

Workflow Diagram:

Delivery 1 ----> INSERT webhook_event (ok) -> create Credit -> COMMIT -> 200
Delivery 2 ----> INSERT webhook_event -> UNIQUE violation
-> savepoint rolled back -> return False -> 200 (no-op)
Delivery 3 (concurrent with 1)
-> INSERT blocks on the uniqueness check until 1 commits
-> UNIQUE violation -> no-op

If Credit creation fails -> whole transaction rolls back -> event row gone -> retry can succeed

🔍 Interviewer Notes: Look for "the database enforces uniqueness, the application handles the conflict," knowledge of the savepoint requirement when catching IntegrityError inside atomic(), and the insight that the event record and the side effect must commit together.

❌ Red Flags: if not Model.objects.filter(...).exists(): create() as the only guard; deduplication with an in-memory set or a Redis key with no database constraint; returning 500 on duplicates (the provider retries forever).


Q47: Deep pagination and COUNT(*) make a list endpoint time out​

Level: Senior

Scenario: /api/events/ serves an activity feed for large B2B accounts (hundreds of millions of rows in total). Page 1 takes 3 s and ?page=20000 takes 25 s. Mobile clients use infinite scroll, so they never need page numbers, but they sometimes see duplicate events while scrolling.

Impact: Timeouts on large accounts, database CPU spent counting rows nobody looks at, and duplicate or skipped items in the feed.

Root Cause: PageNumberPagination runs SELECT COUNT(*) over the whole filtered set on every request, plus OFFSET n, which makes the database read and discard n rows. New events inserted at the top shift every offset, which causes the duplicates. The (account_id, created_at) access path has no matching composite index.

Fix:

  1. Switch the feed to CursorPagination: no count, a seek on an indexed column, and stable results under concurrent inserts.
  2. Order by ("-created_at", "-id") and add a composite index that matches the filter plus the ordering.
  3. Cap max_page_size.
  4. For admin-style UIs that truly need page numbers, keep offset pagination but cap the maximum page and consider showing an approximate count.

Code/Syntax Justification:

# feed/models.py
from django.db import models


class Event(models.Model):
account = models.ForeignKey("accounts.Account", on_delete=models.CASCADE)
kind = models.CharField(max_length=50)
payload = models.JSONField(default=dict)
created_at = models.DateTimeField(auto_now_add=True)

class Meta:
indexes = [
models.Index(fields=["account", "-created_at", "-id"], name="event_account_feed_idx"),
]
# feed/pagination.py
from rest_framework.pagination import CursorPagination


class EventFeedPagination(CursorPagination):
page_size = 100
page_size_query_param = "page_size"
max_page_size = 500
ordering = ("-created_at", "-id")
# feed/views.py
from rest_framework import generics

from feed.models import Event
from feed.pagination import EventFeedPagination
from feed.serializers import EventSerializer


class EventFeedView(generics.ListAPIView):
serializer_class = EventSerializer
pagination_class = EventFeedPagination

def get_queryset(self):
return Event.objects.filter(account=self.request.user.account)

Workflow Diagram:

PageNumberPagination, page 20000:
SELECT COUNT(*) FROM event WHERE account_id = 7 (scan all matches)
SELECT ... WHERE account_id = 7 ORDER BY created_at DESC
OFFSET 1999900 LIMIT 100 (read + discard ~2M rows)

CursorPagination:
SELECT ... WHERE account_id = 7 AND created_at < :cursor_ts
ORDER BY created_at DESC, id DESC LIMIT 101 (index seek, constant cost)
response: { "next": "...?cursor=cD0yMDI2...", "previous": ..., "results": [...] }

🔍 Interviewer Notes: Candidates should explain why OFFSET and COUNT get slower with size, and that the cursor's ordering must match an index. Note: DRF builds the cursor position from the first ordering field and uses an offset to break ties, so that field should be nearly unique.

❌ Red Flags: "Add a cache in front of it"; a bigger database instance as the only fix; cursor pagination ordered by a mutable field such as updated_at without understanding how items will jump around.


Q48: cache_page on an authenticated endpoint leaks one user's data to another​

Level: Principal

Scenario: To reduce load, someone added @method_decorator(cache_page(60)) to /api/me/orders/, which uses JWT bearer authentication. Shortly after, a customer reports seeing another customer's order history. Security escalates it as a data breach.

Impact: A personal data leak with regulatory notification obligations (for example under GDPR), loss of trust, and an incident review.

Root Cause: Django's page cache keys on the URL plus the request headers listed in the response's Vary header. With cookie sessions, accessing the session adds Vary: Cookie. With a bearer token in the Authorization header, nothing adds Vary: Authorization automatically, so every user shares one cache entry per URL. The first user's response is served to everyone for 60 seconds. A CDN in front of the app without Cache-Control: private can make it worse.

Fix:

  1. Remove the page cache from user-specific endpoints immediately, and purge the cache.
  2. For per-user data, cache at the data layer with the user ID in the key and explicit invalidation on writes (after commit).
  3. If you really need response caching, add vary_on_headers("Authorization"). It must be applied inside cache_page so the response carries Vary when the cache stores it. Hit rates will be low.
  4. Send Cache-Control: private (or no-store) on authenticated responses so shared caches and CDNs never store them.
  5. Add a test that requests the endpoint as two users and asserts the responses differ.

Code/Syntax Justification:

# BAD: one cache entry shared by all users of this URL
# @method_decorator(cache_page(60), name="list")
# class MyOrdersViewSet(viewsets.ReadOnlyModelViewSet): ...
# orders/cache.py - safe per-user caching at the data layer
from django.core.cache import cache
from django.db import transaction
from django.db.models import Count, Sum

from orders.models import Order


def summary_key(user_id: int) -> str:
return f"orders:summary:v1:{user_id}"


def get_order_summary(user_id: int) -> dict:
key = summary_key(user_id)
data = cache.get(key)
if data is None:
data = Order.objects.filter(customer__user_id=user_id).aggregate(
count=Count("pk"), total=Sum("total", default=0)
)
cache.set(key, data, timeout=60)
return data


def invalidate_order_summary(user_id: int) -> None:
"""Call from every write path that changes a user's orders."""
transaction.on_commit(lambda: cache.delete(summary_key(user_id)))
# orders/views.py
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
from rest_framework.response import Response
from rest_framework.views import APIView

from orders.cache import get_order_summary


@method_decorator(cache_control(private=True, no_store=True), name="dispatch")
class MyOrderSummaryView(APIView):
def get(self, request):
return Response(get_order_summary(request.user.pk))
# If response caching is unavoidable: Vary must be set before cache_page stores it
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_headers
from rest_framework import viewsets

from orders.models import Order
from orders.serializers import OrderSerializer


class MyOrdersViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = OrderSerializer

def get_queryset(self):
return Order.objects.filter(customer__user=self.request.user)

@method_decorator(cache_page(60))
@method_decorator(vary_on_headers("Authorization"))
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)

Workflow Diagram:

BAD:
User A GET /api/me/orders/ -> miss -> view -> response(A) stored under key(URL)
User B GET /api/me/orders/ -> hit key(URL) -> response(A) returned to B [LEAK]

SAFE:
data-layer cache key = orders:summary:v1:<user_id>
response headers: Cache-Control: private, no-store
writes -> on_commit -> cache.delete(key)

🔍 Interviewer Notes: Principal candidates treat this as a security incident first (contain, purge, assess, notify) and a performance problem second. They know exactly how Django builds cache keys and that Vary is the mechanism behind them.

❌ Red Flags: Page-caching any endpoint whose response depends on the user; relying on a CDN's defaults for authenticated APIs; "it's only 60 seconds."


Q49: "Too many connections" after scaling out web and worker pods​

Level: Principal

Scenario: To handle a marketing launch, the team scales from 10 to 40 web pods (4 gunicorn workers each, threaded) and adds Celery workers. PostgreSQL starts rejecting connections with FATAL: sorry, too many clients already. Requests fail at random, and even the migration job can't connect.

Impact: A site-wide outage during peak traffic, caused by scaling up.

Root Cause: Every Django worker thread holds its own database connection. With CONN_MAX_AGE set to keep connections open, idle ones are never returned. Total demand = pods × processes × threads (+ Celery concurrency + cron jobs + admin tools), which far exceeds PostgreSQL's max_connections (each Postgres connection is a backend process using real memory). Under ASGI, Django's docs advise against persistent connections; you should use pooling instead.

Fix:

  1. Do the capacity math and set a per-pod connection budget: sum(all clients) < max_connections - reserved.
  2. Use a connection pool:
    • Django 5.1+ with psycopg 3: native pooling via "OPTIONS": {"pool": {...}} (requires psycopg[pool]). Size it per process and set CONN_MAX_AGE = 0, because pooling replaces persistent connections.
    • PgBouncer in transaction mode for very large fleets. Set DISABLE_SERVER_SIDE_CURSORS = True and avoid session-level features (session SET, advisory locks held across transactions).
  3. Enable CONN_HEALTH_CHECKS = True (Django 4.1+) when using persistent connections, so dead connections are replaced.
  4. Cap Celery concurrency, and give migration and admin jobs a reserved budget.
  5. Alert on connection usage (pg_stat_activity count versus max_connections) before it hits the wall.

Code/Syntax Justification:

# settings/production.py - Django 5.1+ native pool (psycopg 3)
import os

DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.environ["DB_NAME"],
"USER": os.environ["DB_USER"],
"PASSWORD": os.environ["DB_PASSWORD"],
"HOST": os.environ["DB_HOST"],
"PORT": os.environ.get("DB_PORT", "5432"),
"CONN_MAX_AGE": 0, # pooling replaces persistent connections
"OPTIONS": {
"pool": {
"min_size": 1,
"max_size": 4, # per process: budget = pods x processes x 4
"timeout": 10, # seconds to wait for a free connection
},
},
}
}
# settings/production_pgbouncer.py - alternative: PgBouncer in transaction mode
from .production import * # noqa: F403

DATABASES["default"]["HOST"] = "pgbouncer.internal" # noqa: F405
DATABASES["default"]["OPTIONS"] = {} # noqa: F405 (no app-side pool)
DATABASES["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True # noqa: F405

Workflow Diagram:

Demand without a budget:
40 pods x 4 processes x 8 threads = 1280 connections
+ Celery 10 workers x 8 = 80
+ cron / admin / migrations = ~10
---------------------------------------------
~1370 > max_connections (e.g. 500) -> FATAL: too many clients

With pooling:
40 pods x 4 processes x pool max 4 = 640 -> still too high -> lower max_size or add PgBouncer
App pools -> PgBouncer (transaction mode) -> 100 real Postgres connections

🔍 Interviewer Notes: Look for explicit capacity math, knowing that connections belong to threads or processes (not to pods), and the PgBouncer transaction-mode caveats. Principal candidates also question whether more pods were the right fix, given that the database was the real bottleneck.

❌ Red Flags: Raising max_connections to 5000; CONN_MAX_AGE = None everywhere without health checks; using PgBouncer transaction mode with server-side cursors still enabled.


Q50: A post_save signal causes infinite recursion and stale totals​

Level: Senior

Scenario: A post_save receiver on Order recalculates Customer.total_spent and then calls instance.save() to "persist a flag." Saving an order now hits RecursionError in some code paths. Meanwhile, the nightly job that marks thousands of orders as paid with QuerySet.update() leaves every customer's total_spent stale, because signals never fired.

Impact: Crashing writes, wrong customer totals in billing and CRM, and a team afraid to touch the order model.

Root Cause:

  • Calling instance.save() inside a post_save receiver for the same model triggers the receiver again, which recurses.
  • QuerySet.update(), bulk_create() (no post_save), bulk_update() and raw SQL don't send the pre_save/post_save signals, so logic kept in signals is silently skipped on bulk paths.
  • Signal receivers are implicit: they run synchronously inside the caller's transaction, aren't visible at the call site, and make costs and side effects hard to reason about.

Fix:

  1. Move the business rule into an explicit service function that every write path (single and bulk) calls.
  2. Recompute aggregates in SQL (aggregate + update) rather than in Python loops, and avoid re-saving the triggering instance.
  3. If a signal must remain (for example, cross-app decoupling), keep it tiny, use update_fields/queryset update() instead of save(), and defer side effects with transaction.on_commit.
  4. Add a test for the bulk path that asserts totals are correct.

Code/Syntax Justification:

# BAD
from django.db.models.signals import post_save
from django.dispatch import receiver

from shop.models import Order


@receiver(post_save, sender=Order)
def update_customer_total(sender, instance, **kwargs):
customer = instance.customer
customer.total_spent = sum(o.total for o in customer.orders.all()) # loads every order
customer.save()
instance.totals_synced = True
instance.save() # fires post_save again -> recursion
# GOOD: explicit service used by single and bulk paths
from django.db import transaction
from django.db.models import Sum

from crm.models import Customer
from shop.models import Order


def recalculate_customer_total(customer_id: int) -> None:
total = Order.objects.filter(customer_id=customer_id, status="paid").aggregate(
total=Sum("total", default=0)
)["total"]
Customer.objects.filter(pk=customer_id).update(total_spent=total)


def mark_orders_paid(order_ids: list[int]) -> None:
with transaction.atomic():
customer_ids = set(
Order.objects.filter(pk__in=order_ids).values_list("customer_id", flat=True)
)
Order.objects.filter(pk__in=order_ids).update(status="paid")
for customer_id in customer_ids:
recalculate_customer_total(customer_id)


def mark_order_paid(order: Order) -> None:
with transaction.atomic():
order.status = "paid"
order.save(update_fields=["status"])
recalculate_customer_total(order.customer_id)

Workflow Diagram:

BAD:
order.save() -> post_save -> customer.save() -> instance.save() -> post_save -> ... RecursionError
Order.objects.update(status="paid") -> (no signal) -> total_spent stale

GOOD:
mark_order_paid() ---\
+--> recalculate_customer_total() (SQL SUM + UPDATE)
mark_orders_paid() ---/ same transaction, explicit, testable

🔍 Interviewer Notes: Senior candidates know exactly which ORM operations skip signals and prefer explicit services for business rules. Ask when they would still use signals (for example, decoupled third-party app hooks or cache invalidation, kept small).

❌ Red Flags: Calling save() on the sender inside its own post_save; "fixing" recursion with a global flag or by disconnecting the signal at runtime; business-critical logic that exists only in signals.