﻿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
37545	"Quadratic _get_altered_foo_together_operations(""index_together"") calls in MigrationAutodetector."	Robert Lechte		"In `django/db/migrations/autodetector.py`, `MigrationAutodetector.create_altered_indexes()` iterates over every model in `sorted(self.kept_model_keys)` and, inside that loop, calls `self._get_altered_foo_together_operations(operations.AlterIndexTogether.option_name)`:

{{{
#!python
for app_label, model_name in sorted(self.kept_model_keys):
    ...
    for (
        old_value,
        new_value,
        index_together_app_label,
        index_together_model_name,
        dependencies,
    ) in self._get_altered_foo_together_operations(
        operations.AlterIndexTogether.option_name
    ):
        if (
            app_label != index_together_app_label
            or model_name != index_together_model_name
        ):
            continue
        ...
}}}

`_get_altered_foo_together_operations()` itself sorts and iterates over all of `self.kept_model_keys`, making `create_altered_indexes()` O(models^2). This runs on every `makemigrations` invocation and on every `migrate` invocation (which runs the autodetector to check for unmigrated model changes).

Nothing read by `_get_altered_foo_together_operations()` (`from_state`, `to_state`, `kept_model_keys`, `renamed_models`, `renamed_fields`) is modified during the loop.

=== Impact ===

* Synthetic benchmark (autodetecting changes between two 1,000-model states): **0.70s** on `main` vs **0.28s** after hoisting the call out of the loop.


=== Proposed fix ===

Call `self._get_altered_foo_together_operations(operations.AlterIndexTogether.option_name)` once before the `for app_label, model_name in sorted(self.kept_model_keys):` loop, grouping the results by `(app_label, model_name)`. This preserves detection of historical `index_together` → `Meta.indexes` renames while reducing the loop from O(N^2) to O(N).

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
