﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
37544	ProjectState.alter_field() runs field_is_referenced() scan even when models are unrendered	Robert Lechte		"In `django/db/migrations/state.py`, `ProjectState.alter_field()` unconditionally computes:

{{{
#!python
delay = not field.is_relation and not field_is_referenced(
    self, model_key, (name, field)
)
self.reload_model(*model_key, delay=delay)
}}}

`field_is_referenced()` scans every field of every model in the `ProjectState`, but `reload_model()` immediately checks `if ""apps"" in self.__dict__:` and does nothing when the state's models have not been rendered.

When `migrate` builds the project state by replaying migration history, the `ProjectState` is unrendered throughout, so `field_is_referenced()` performs an O(total fields in project) scan on every `AlterField` operation only for the result to be discarded—making history replay quadratic in the number of fields/alterations.

=== Impact ===

* Synthetic benchmark (1,000-model unrendered `ProjectState`, 1,000 `alter_field()` calls): **1.14s** on `main` vs **<0.01s** with the check guarded by `if ""apps"" in self.__dict__:`.


=== Proposed fix ===

Guard the `delay` computation and `self.reload_model()` call in `ProjectState.alter_field()` with `if ""apps"" in self.__dict__:` (the same check `reload_model()` already uses). Behavior for rendered states is unchanged.

I have a patch with regression tests ready and will open a PR referencing this ticket."	Uncategorized	new	Migrations	dev	Normal				Unreviewed	0	0	0	0	0	0
