#37544 new Uncategorized

ProjectState.alter_field() runs field_is_referenced() scan even when models are unrendered

Reported by: Robert Lechte Owned by:
Component: Migrations Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

In django/db/migrations/state.py, ProjectState.alter_field() unconditionally computes:

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.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top