From 8e2460d599aec95f8cfe514d3cc8acdd4ca4b1fb Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Wed, 3 May 2023 13:06:19 +0200 Subject: Fixed #34529, Refs #34525 -- Reduced index operations with Meta.indexes/index_together when optimizing migrations. This makes squashing migrations an available path for changing Meta.index_together, which is deprecated, to Meta.indexes. Follow up to f81032572107846922745b68d5b7191058fdd5f5. --- django/db/migrations/operations/models.py | 65 +++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) (limited to 'django') diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py index b89b6b511b..9c5bd5fbcb 100644 --- a/django/db/migrations/operations/models.py +++ b/django/db/migrations/operations/models.py @@ -303,6 +303,71 @@ class CreateModel(ModelOperation): managers=self.managers, ), ] + elif ( + isinstance(operation, IndexOperation) + and self.name_lower == operation.model_name_lower + ): + if isinstance(operation, AddIndex): + return [ + CreateModel( + self.name, + fields=self.fields, + options={ + **self.options, + "indexes": [ + *self.options.get("indexes", []), + operation.index, + ], + }, + bases=self.bases, + managers=self.managers, + ), + ] + elif isinstance(operation, RemoveIndex): + options_indexes = [ + index + for index in self.options.get("indexes", []) + if index.name != operation.name + ] + return [ + CreateModel( + self.name, + fields=self.fields, + options={ + **self.options, + "indexes": options_indexes, + }, + bases=self.bases, + managers=self.managers, + ), + ] + elif isinstance(operation, RenameIndex) and operation.old_fields: + options_index_together = { + fields + for fields in self.options.get("index_together", []) + if fields != operation.old_fields + } + if options_index_together: + self.options["index_together"] = options_index_together + else: + self.options.pop("index_together", None) + return [ + CreateModel( + self.name, + fields=self.fields, + options={ + **self.options, + "indexes": [ + *self.options.get("indexes", []), + models.Index( + fields=operation.old_fields, name=operation.new_name + ), + ], + }, + bases=self.bases, + managers=self.managers, + ), + ] return super().reduce(operation, app_label) -- cgit v1.2.1