Real-world mechanisms, state management, edge cases, performance trade-offs, and practical coding.
books and touching book.author fires one query per book (N+1).Book.objects.select_related("author").Books.prefetch_related("tags").select_related("author__profile")), Prefetch objects allow filtered prefetches.
Detection: django-debug-toolbar, nplusone, or assertNumQueries in tests. Always name the detection tool — interviews love that.if queryset: executes — surprising DB hit in conditionals; use .exists().from django.db.models import F, Q
Book.objects.update(views=F("views") + 1) # atomic in SQL
Book.objects.filter(Q(year=2024) | Q(isbn__isnull=True))
&/| and parentheses.
Advanced note: F also enables comparisons between fields and optimistic concurrency via conditional update returning rowcount.from django.db import transaction
with transaction.atomic():
book = Book.objects.select_for_update().get(pk=pk)
book.stock -= 1; book.save()
atomic() wraps a block/decorator in BEGIN…COMMIT/ROLLBACK; nested atomics become savepoints.select_for_update() locks rows until commit — pair INSIDE atomic, else no-op.transaction.on_commit(fn) defers side effects (emails, cache busts) until data is durable — classic interview favorite.
Autocommit default means EVERY statement commits alone unless wrapped — say it explicitly.pre_save/post_save, pre_delete/post_delete, m2m_changed, request_started...save()/delete() explicitly, service layer functions, or transaction.on_commit hooks for reactions.
If signals stay: keep them thin (enqueue task only), document loudly, register receivers in AppConfig.ready().You've completed the 5 free sample questions. Get unrestricted lifetime access to every question, model answer, implementation challenge, and all 27+ technologies for a single payment.
₹399 India / $9 International · One-time settlement · Zero subscription