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

# 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` (`django/db/models/base.py:Model.delete`) or `QuerySet.delete` constructs a **`Collector`** (`django/db/models/deletion.py:Collector`), walks the reverse foreign-key graph in `Collector.collect`, and executes the resulting plan inside `Collector.delete`.

## Fast delete vs. full collection on `"Desk('metro').delete()"`

```text figure=collector-cascade
Collector cascade graph & fast delete on Desk('metro').delete() (Django 6.1.3)

1. Cascade graph on desk/ (no signals):
   Collected in Python (Collector.data):  Desk (1) -> Reporter (2) -> Story (3)
   Fast-deleted in SQL (fast_deletes):    Correction, StoryBeat*, Subscription (cross-app from subscribers!)
   *Connecting 1 post_delete receiver on StoryBeat moves all 4 StoryBeat rows from fast_deletes into Collector.data.

2. Deleting 200 Correction rows (median of 5 trials):
   Fast delete (no signals):         0.293 ms · 1 SQL ·   0 rows hydrated  (1.0x)
   +1 post_delete receiver:          3.171 ms · 3 SQL · 200 rows hydrated (10.8x)
```

*Every row count, SQL count, and bar is parsed from `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.can_fast_delete`** (`django/db/models/deletion.py:Collector.can_fast_delete`). 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:

1. `Collector.force_collection` is `False` (the Django admin's delete confirmation screen uses `NestedObjects` / `force_collection=True` so it can list every doomed row before deleting!).
2. If reached via a cascade (`"from_field"`), that FK's `on_delete` is `CASCADE` (`django/db/models/deletion.py:CASCADE`).
3. **Neither `pre_delete` (`django/db/models/signals.py:pre_delete`) nor `post_delete` (`django/db/models/signals.py:post_delete`) has any listeners registered for that model** (`_has_signal_listeners`, lines 205–208).
4. The model has no multi-table parent links (other than `"from_field"`) and no `GenericRelation` / `bulk_related_objects` private fields.
5. Every reverse foreign key pointing *at* this model (from `get_candidate_relations_to_delete`) has its `on_delete` inside **`SKIP_COLLECTION`** (`django/db/models/deletion.py:SKIP_COLLECTION`) — either `DO_NOTHING` or **Django `6.1`'s new database-level handlers `DB_CASCADE`, `DB_SET_NULL`, and `DB_SET_DEFAULT`** (`DatabaseOnDelete`, lines 84–103), which delegate cascade work straight to SQL `ON DELETE` constraints!

When `can_fast_delete` returns `False`, `Collector.collect` (`django/db/models/deletion.py:Collector.collect`) 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 unevaluated `QuerySet` to `Collector.fast_deletes` — **zero `"SELECT"` queries and zero Python instances**!
- Otherwise, `Collector` queries child rows in backend-sized batches (`get_del_batches`), optimizing by calling `QuerySet.only` on 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's `on_delete` callable:
  - `CASCADE` recurses into `Collector.collect` and records a dependency edge (`Collector.dependencies`).
  - `PROTECT` (`django/db/models/deletion.py:PROTECT`) raises `ProtectedError` immediately; `RESTRICT` (`django/db/models/deletion.py:RESTRICT`) records `restricted_objects` and checks at the end (lines 407–431) whether every restricted row is *also* being deleted by a parallel `CASCADE` path before raising `RestrictedError`!
  - `SET_NULL` (`django/db/models/deletion.py:SET_NULL`), `SET_DEFAULT`, and `SET(...)` record batched `"UPDATE"` instructions in `Collector.field_updates` (note `SET_NULL.lazy_sub_objs = True`, line 73, allowing an unevaluated queryset to run a single SQL `"UPDATE ... SET user_id = NULL"`!).

## Execution order inside `Collector.delete`

Open `Collector.delete` (`django/db/models/deletion.py:Collector.delete`):

1. **Single-row leaf shortcut (lines 478–487):** Deleting one `"Correction"` with no dependencies skips `transaction.atomic` completely and executes a single `DeleteQuery.delete_batch` (`1` query, `0` `"SELECT"`s).
2. **Topological sort (`Collector.sort`, lines 448–464):** Orders `Collector.data` so dependent child tables are deleted *before* the parent tables they reference, preventing foreign-key constraint violations even on databases that cannot defer constraint checks.
3. **One `transaction.atomic(savepoint=False)` block (lines 489–548):**
   - Fires `pre_delete` for every collected instance in `Collector.data`.
   - Runs every queryset in `Collector.fast_deletes` via `_raw_delete` (deleting leaf tables first!).
   - Executes every batched `"UPDATE"` in `Collector.field_updates` (such as `SET_NULL` clearing `"Reporter.user_id"` when a `"User"` is deleted!).
   - Deletes each model in `Collector.data` via `DeleteQuery.delete_batch` and fires `post_delete` for every collected instance.
4. Finally (lines 549–551), sets `pk = None` on 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:

```text recording=ch06-models
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`):

```text recording=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.connect` on `post_delete` with `sender=None`) disables fast delete across your ENTIRE project!** Because `Signal.has_listeners(model)` returns `True` for every model whenever a wildcard receiver is registered, one audit-log library connecting a senderless `post_delete` receiver silently strips fast delete from every table in the database.
- **Custom `Model.delete` overrides are NOT called by `QuerySet.delete` or `CASCADE`.** `Collector.delete` executes SQL directly through `DeleteQuery` and `_raw_delete`; if you rely on soft-delete logic inside `Model.delete()`, a bulk `"Story.objects.filter(...).delete()"` or cascading `"desk.delete()"` will permanently hard-delete the rows!
- **Mixing Python `CASCADE` and Django `6.1`'s `DB_CASCADE` in the same reference chain is rejected by system checks (`"fields.E324"` and mixed-variant checks in `ForeignKey._check_on_delete`).** And remember that `DB_CASCADE` skips `Collector` completely, so `pre_delete` / `post_delete` signals 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](inheritance.md).
