---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# Directing AI agents with a model of Django internals

What six questions catch 90% of subtle bugs in agent-generated Django code before it reaches production?

Coding agents are extraordinarily good at writing idiomatic Django syntax — models, serializers, `ModelForm`s, `ModelAdmin` subclasses, migrations, and `TestCase` suites that pass on the first run. Yet agents share the exact same blind spot as rushed human engineers: they reason **one file at a time**, relying heavily on older Django `3.x`/`4.x` conventions, and rarely simulate what happens when two layers meet under production load, concurrency, or real rollbacks.

When you carry a concrete mental model of Django `6.1.3`'s internals, you stop reading generated code line-by-line for syntax errors and start asking **six targeted seam questions** that catch almost every subtle production bug before merge.

## 1. Query count and `fetch_mode`: what SQL runs when the template renders?

Never accept a view, serializer, or `ModelAdmin` change just because the unit test returns HTTP `200`. Ask:

- **How many SQL queries does this endpoint execute at `N = 25` rows, and did you test it with `assertNumQueries` or `QuerySet.fetch_mode` with `FETCH_RAISE`?**
- Remember Chapters 7, 8, 11, and 14: a lazy `QuerySet` looks query-free in the view and explodes to `81` SQL queries inside `"edition.html"`; a single custom `"list_display"` callable disables `ChangeList`'s automatic `select_related` and turns a 25-row admin page into `80` queries; two `Count()` annotations over independent multi-valued relations produce a silent Cartesian fan-out unless replaced by correlated `Subquery` expressions; and `"if qs:"` before `"qs[:N]"` hydrates the whole table into memory!

## 2. Transaction and `on_commit` boundaries: what happens on ROLLBACK?

Whenever generated code saves models AND touches anything outside the database — enqueueing a `django.tasks` job, sending email, invalidating a shared cache, deleting a `FieldFile`, or calling an external API — ask:

- **Is every external side effect deferred inside `django.db.transaction.on_commit`, and did the test use `TestCase.captureOnCommitCallbacks(execute=True)`?**
- Remember Chapters 9, 12, and 13: calling `Task.enqueue` inside `django.db.transaction.atomic` leaks ghost jobs when the transaction rolls back (or races uncommitted rows!), calling `Model.delete()` intentionally leaves files in storage, and `TestCase`'s uncommitted outer transaction means `on_commit` callbacks are silently skipped unless explicitly captured in tests!

## 3. Sync vs. async chain mode: is this endpoint actually running on the event loop?

Whenever an agent writes `"async def"` views or suggests moving to ASGI for performance, ask:

- **Are ALL entries in `"MIDDLEWARE"` marked `async_capable = True`, and does the view use `await request.auser()` and async ORM methods (`aget`/`acount`)?**
- Remember Chapters 3, 11, and 14: one synchronous middleware forces `BaseHandler.adapt_method_mode` into `sync_to_async` thread-pool hops (making `"desk/"`'s edition page `1.76x` slower under ASGI than plain WSGI!), and touching synchronous `"request.user"` inside an async view trips `SynchronousOnlyOperation`!

## 4. Cache keys, Vary, and process-local state: what leaks across users or workers?

Whenever generated code caches responses, modifies sessions, writes custom template `Node` (`django/template/base.py:Node`) subclasses, or stores attributes on a `ModelAdmin` or `View`, ask:

- **Is any per-request state stored on a process-shared object (`Node`, `ModelAdmin`, `BaseForm.base_fields`), does `"MIDDLEWARE"` keep `UpdateCacheMiddleware` first and `FetchFromCacheMiddleware` last, and are we avoiding `LocMemCache` in multi-worker production?**
- Remember Chapters 10, 11, and 12: cached `Template` (`django/template/base.py:Template`) `Node`s and `AdminSite._registry` `ModelAdmin` instances live for the entire worker lifetime (per-render node state belongs in `RenderContext`), touching `"request.session"` stamps `"Vary: Cookie"`, `LocMemCache` silently splits across Gunicorn workers, and `ModelBackend` caches permissions on `"user._perm_cache"` for the lifetime of the Python `User` object!

## 5. Migrations, `ProjectState`, and forms: what mutates in memory or locks tables?

Whenever an agent generates a migration or overrides `BaseModelForm.clean`, ask:

- **Does the data migration use historical `Apps.get_model` models (never live imports), does the schema change trigger a full table rewrite or long lock, and does `BaseModelForm.clean` call `super().clean()` while guarding against invalid-form instance mutation?**
- Remember Chapters 9 and 10: importing a live model inside `RunPython` crashes future migrations when fields later change, altering a column on SQLite rewrites the entire table (`_remake_table`), forgetting `super().clean()` on a `ModelForm` silently disables `validate_unique()` and `validate_constraints()`, and `BaseModelForm._post_clean` mutates `"form.instance"` in memory *even when `is_valid()` returns `False`*!

## 6. Test blind spots: what did `Client()` silently skip?

Whenever an agent delivers a green test suite, ask:

- **Did we test unsafe `"POST"` endpoints with `Client(enforce_csrf_checks=True)`, verify `"manage.py check --deploy"` against production settings, and avoid paying `TransactionTestCase` table flushes where `TestCase` + `setUpTestData` suffices?**
- Remember Chapter 13: default `Client()` sets `"_dont_enforce_csrf_checks = True"`, static `"manage.py check"` skips all `21` deployment security checks (`W004`/`W008`/`W012`/`W016`), and `TestCase` savepoint rollbacks run `20x` faster than `TransactionTestCase` flushes!

---

Every abstraction in Django earns its keep by hiding real mechanical complexity behind clean Python. Knowing what sits underneath — from `WSGIHandler` and `URLResolver` through `ModelBase`, `SQLCompiler`, `atomic`, `NodeList`, `BaseForm`, `AdminSite`, `Task`, and `TestCase` — does not mean fighting Django's abstractions. It means trusting them right up to the exact line where they leak, and knowing immediately where to look in the source when they do.
