6.6 Models, metaclasses, and state
Collector, cascades, and fast deletes
How does Model.delete walk every foreign key pointing at a row, when can it collapse deletions into a single SQL statement, and why can one signal receiver force Django to load thousands of rows into memory?
Unlike raw SQL — where DELETE FROM newsroom_desk WHERE id = 1 relies on database-side ON DELETE CASCADE triggers — Django historically emulated on_delete cascades in Python so that pre_delete / post_delete signals fire, PROTECT and RESTRICT raise rich Python exceptions, and behavior stays uniform across every SQL backend.
Every call to Model.delete or QuerySet.delete constructs a Collector, walks the reverse foreign-key graph in Collector, and executes the resulting plan inside Collector.delete.
Fast delete vs. full collection on "Desk('metro').delete()"
ch06-models and ch06-bench. Look at how deleting a single newsroom desk automatically walks across app boundaries into the "subscribers" app’s "Subscription" table, keeps leaf tables on the SQL fast path, and falls off a 10.8x performance cliff the moment one signal receiver attaches to a leaf model.Inside Collector.can_fast_delete and Collector.collect
Open Collector. Django can fast delete a model or queryset — issuing a direct DELETE FROM ... WHERE ... without running a "SELECT" to hydrate rows into Python — if and only if five conditions hold simultaneously:
Collectoris.force_collection False(the Django admin’s delete confirmation screen usesNestedObjects/force_collection=Trueso it can list every doomed row before deleting!).- If reached via a cascade (
"from_field"), that FK’son_deleteisCASCADE. - Neither
pre_deletenorpost_deletehas any listeners registered for that model (_has_signal_listeners, lines 205–208). - The model has no multi-table parent links (other than
"from_field") and noGenericRelation/bulk_related_objectsprivate fields. - Every reverse foreign key pointing at this model (from
get_candidate_relations_to_delete) has itson_deleteinsideSKIP_COLLECTION— eitherDO_NOTHINGor Django6.1’s new database-level handlersDB_CASCADE,DB_SET_NULL, andDB_SET_DEFAULT(DatabaseOnDelete, lines 84–103), which delegate cascade work straight to SQLON DELETEconstraints!
When can_fast_delete returns False, Collector walks every reverse N-1 and 1-1 relation:
- If the child model itself qualifies for
can_fast_delete(related_model, from_field=field)(like"Correction","StoryBeat", and"Subscription"when deleting a"Desk"), Django appends an unevaluatedQuerySettoCollector— zero.fast_deletes "SELECT"queries and zero Python instances! - Otherwise,
Collectorqueries child rows in backend-sized batches (get_del_batches), optimizing by callingQuerySet.onlyon the referenced fields when no signal receivers exist on the child model (lines 365–377) so huge text blobs stay out of RAM, and dispatches the field’son_deletecallable:CASCADErecurses intoCollectorand records a dependency edge (.collect Collector)..dependencies PROTECTraisesProtectedErrorimmediately;RESTRICTrecordsrestricted_objectsand checks at the end (lines 407–431) whether every restricted row is also being deleted by a parallelCASCADEpath before raisingRestrictedError!SET_NULL,SET_DEFAULT, andSET(...)record batched"UPDATE"instructions inCollector(note.field_updates SET_NULL, line 73, allowing an unevaluated queryset to run a single SQL.lazy_sub_objs = True "UPDATE ... SET user_id = NULL"!).
Execution order inside Collector.delete
Open Collector.delete:
- Single-row leaf shortcut (lines 478–487): Deleting one
"Correction"with no dependencies skipstransactioncompletely and executes a single.atomic DeleteQuery(.delete_batch 1query,0"SELECT"s). - Topological sort (
Collector.sort, lines 448–464): OrdersCollector.dataso dependent child tables are deleted before the parent tables they reference, preventing foreign-key constraint violations even on databases that cannot defer constraint checks. - One
transactionblock (lines 489–548):.atomic(savepoint=False) - Fires
pre_deletefor every collected instance inCollector.data. - Runs every queryset in
Collectorvia.fast_deletes _raw_delete(deleting leaf tables first!). - Executes every batched
"UPDATE"inCollector(such as.field_updates SET_NULLclearing"Reporterwhen a.user_id" "User"is deleted!). - Deletes each model in
Collector.dataviaDeleteQueryand fires.delete_batch post_deletefor every collected instance.
- Fires
- Finally (lines 549–551), sets
pk = Noneon every deleted Python instance in memory (leaving"_state.adding"unchanged — notice that re-saving a deleted instance will insert a fresh row!).
Watch leaf fast delete, cross-app "Desk" cascade, the single-signal trap, and SET_NULL execute live on our newsroom app:
Collector, cascades, fast deletes, SET_NULL, and the signal trap
Correction leaf can_fast_delete: True
leaf Correction.delete() -> SQL ops=['DELETE'] (1 query, 0 SELECTs)
Desk('metro') collect (no signals): fast_deletes=['Correction', 'StoryBeat', 'Subscription'] data={'Desk': 1, 'Reporter': 2, 'Story': 3}
Desk('metro').delete() (no signals): total=13 queries=9 ops=['SELECT', 'SELECT', 'SELECT', 'DELETE', 'DELETE', 'DELETE', 'DELETE', 'DELETE', 'DELETE']
Desk('metro') collect (+post_delete on StoryBeat): fast_deletes=['Correction', 'Subscription'] data={'Desk': 1, 'Reporter': 2, 'Story': 3, 'StoryBeat': 4}
Desk('metro').delete() (+post_delete on StoryBeat): total=13 queries=10 ops=['SELECT', 'SELECT', 'SELECT', 'SELECT', 'DELETE', 'DELETE', 'DELETE', 'DELETE', 'DELETE', 'DELETE']
User.delete() with Reporter.user SET_NULL -> reporter.user_id=None update_sql=UPDATE "newsroom_reporter" SET "user_id" = %s WHERE "newsroom_reporter"."user_id" IN (%s)
And look at the cost of that single post_delete receiver when deleting 200 "Correction" rows (ch06-bench):
Deleting 200 Correction rows: fast delete vs 1 post_delete receiver (5 trials)
path median_ms sql_queries hydrated_rows relative
fast delete (no signal listeners) 0.293 1 0 1.00x
signal-forced Collector (+1 post_delete) 3.171 3 200 10.84x
From 0.293 ms (1 "DELETE", 0 Python objects) to 3.171 ms (3 queries, 200 hydrated model instances, 200 signal dispatches — 10.84x slower!) — and on a production table with 500,000 rows, a single stray post_delete receiver turns a 50-millisecond SQL "DELETE" into an out-of-memory worker crash!
Where Collector and deletion leak
- Connecting a global signal (
Signal.connectonpost_deletewithsender=None) disables fast delete across your ENTIRE project! BecauseSignalreturns.has_listeners(model) Truefor every model whenever a wildcard receiver is registered, one audit-log library connecting a senderlesspost_deletereceiver silently strips fast delete from every table in the database. - Custom
Model.deleteoverrides are NOT called byQuerySet.deleteorCASCADE.Collector.deleteexecutes SQL directly throughDeleteQueryand_raw_delete; if you rely on soft-delete logic insideModel.delete(), a bulk"Storyor cascading.objects .filter(...).delete()" "desk.delete()"will permanently hard-delete the rows! - Mixing Python
CASCADEand Django6.1’sDB_CASCADEin the same reference chain is rejected by system checks ("fields.E324"and mixed-variant checks inForeignKey). And remember that._check_on_delete DB_CASCADEskipsCollectorcompletely, sopre_delete/post_deletesignals will not fire for rows deleted by the database engine.
We have traced single-table creation, metadata, descriptors, state, saving, and cascading deletion. One final design lever shapes every table and query a model produces: Python class inheritance, which we dissect in Abstract bases, multi-table joins, and proxies.