From 191f6a9a4586b5e5f79f4f42f190e7ad4bbacc84 Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Mon, 1 May 2023 18:57:24 +0200 Subject: [PATCH] Fixed #34528 -- Reduced Add/RemoveIndex operations when optimizing migrations. --- django/db/migrations/operations/models.py | 5 +++++ tests/migrations/test_optimizer.py | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py index 967a91fdc8..b89b6b511b 100644 --- a/django/db/migrations/operations/models.py +++ b/django/db/migrations/operations/models.py @@ -861,6 +861,11 @@ class AddIndex(IndexOperation): def migration_name_fragment(self): return "%s_%s" % (self.model_name_lower, self.index.name.lower()) + def reduce(self, operation, app_label): + if isinstance(operation, RemoveIndex) and self.index.name == operation.name: + return [] + return super().reduce(operation, app_label) + class RemoveIndex(IndexOperation): """Remove an index from a model.""" diff --git a/tests/migrations/test_optimizer.py b/tests/migrations/test_optimizer.py index 8cd4c67fbd..2f6616ad5b 100644 --- a/tests/migrations/test_optimizer.py +++ b/tests/migrations/test_optimizer.py @@ -1158,3 +1158,17 @@ class OptimizerTests(SimpleTestCase): ), ] ) + + def test_add_remove_index(self): + self.assertOptimizesTo( + [ + migrations.AddIndex( + "Pony", + models.Index( + fields=["weight", "pink"], name="idx_pony_weight_pink" + ), + ), + migrations.RemoveIndex("Pony", "idx_pony_weight_pink"), + ], + [], + )