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, ModelForms, 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 = 25rows, and did you test it withassertNumQueriesorQuerySetwith.fetch_mode FETCH_RAISE? - Remember Chapters 7, 8, 11, and 14: a lazy
QuerySetlooks query-free in the view and explodes to81SQL queries inside"edition.html"; a single custom"list_display"callable disablesChangeList’s automaticselect_relatedand turns a 25-row admin page into80queries; twoCount()annotations over independent multi-valued relations produce a silent Cartesian fan-out unless replaced by correlatedSubqueryexpressions; 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, and did the test use.db .transaction .on_commit TestCase?.captureOnCommitCallbacks(execute=True) - Remember Chapters 9, 12, and 13: calling
Task.enqueueinsidedjangoleaks ghost jobs when the transaction rolls back (or races uncommitted rows!), calling.db .transaction .atomic Model.delete()intentionally leaves files in storage, andTestCase’s uncommitted outer transaction meanson_commitcallbacks 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"markedasync_capable = True, and does the view useawait requestand async ORM methods (.auser() aget/acount)? - Remember Chapters 3, 11, and 14: one synchronous middleware forces
BaseHandlerinto.adapt_method_mode sync_to_asyncthread-pool hops (making"desk/"'s edition page1.76xslower under ASGI than plain WSGI!), and touching synchronous"request.user"inside an async view tripsSynchronousOnlyOperation!
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 subclasses, or stores attributes on a ModelAdmin or View, ask:
- Is any per-request state stored on a process-shared object (
Node,ModelAdmin,BaseForm), does.base_fields "MIDDLEWARE"keepUpdateCacheMiddlewarefirst andFetchFromCacheMiddlewarelast, and are we avoidingLocMemCachein multi-worker production? - Remember Chapters 10, 11, and 12: cached
TemplateNodes andAdminSite._registry ModelAdmininstances live for the entire worker lifetime (per-render node state belongs inRenderContext), touching"requeststamps.session" "Vary: Cookie",LocMemCachesilently splits across Gunicorn workers, andModelBackendcaches permissions on"userfor the lifetime of the Python._perm_cache" Userobject!
5. Migrations, ProjectState, and forms: what mutates in memory or locks tables?
Whenever an agent generates a migration or overrides BaseModelForm, ask:
- Does the data migration use historical
Apps.get_modelmodels (never live imports), does the schema change trigger a full table rewrite or long lock, and doesBaseModelFormcall.clean super().clean()while guarding against invalid-form instance mutation? - Remember Chapters 9 and 10: importing a live model inside
RunPythoncrashes future migrations when fields later change, altering a column on SQLite rewrites the entire table (_remake_table), forgettingsuper().clean()on aModelFormsilently disablesvalidate_unique()andvalidate_constraints(), andBaseModelFormmutates._post_clean "form.instance"in memory even whenis_valid()returnsFalse!
6. Test blind spots: what did Client() silently skip?
Whenever an agent delivers a green test suite, ask:
- Did we test unsafe
"POST"endpoints withClient(enforce_csrf_checks=True), verify"manageagainst production settings, and avoid paying.py check --deploy" TransactionTestCasetable flushes whereTestCase+setUpTestDatasuffices? - Remember Chapter 13: default
Client()sets"_dont_enforce_csrf_checks = True", static"manageskips all.py check" 21deployment security checks (W004/W008/W012/W016), andTestCasesavepoint rollbacks run20xfaster thanTransactionTestCaseflushes!
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.