@@ -442,9 +442,17 @@ def _alter_field(self, model, old_field, new_field, old_type, new_type,
442442 # Drop unique constraint, SQL Server requires explicit deletion
443443 self ._delete_unique_constraints (model , old_field , new_field , strict )
444444 # Drop indexes, SQL Server requires explicit deletion
445- self ._delete_indexes (model , old_field , new_field )
446- if not new_field .get_internal_type () in ("JSONField" , "TextField" ) and not (old_field .db_index and new_field .db_index ):
447- post_actions .append ((self ._create_index_sql (model , [new_field ]), ()))
445+ indexes_dropped = self ._delete_indexes (model , old_field , new_field )
446+ if (
447+ new_field .get_internal_type () not in ("JSONField" , "TextField" ) and
448+ (old_field .db_index or not new_field .db_index ) and
449+ new_field .db_index or
450+ (indexes_dropped and sorted (indexes_dropped ) == sorted (
451+ [index .name for index in model ._meta .indexes ]))
452+ ):
453+ create_index_sql_statement = self ._create_index_sql (model , [new_field ])
454+ if create_index_sql_statement .__str__ () not in [sql .__str__ () for sql in self .deferred_sql ]:
455+ post_actions .append ((create_index_sql_statement , ()))
448456 # Only if we have a default and there is a change from NULL to NOT NULL
449457 four_way_default_alteration = (
450458 new_field .has_default () and
@@ -566,7 +574,9 @@ def _alter_field(self, model, old_field, new_field, old_type, new_type,
566574 if index_columns :
567575 for columns in index_columns :
568576 create_index_sql_statement = self ._create_index_sql (model , columns )
569- if create_index_sql_statement .__str__ () not in [sql .__str__ () for sql in self .deferred_sql ]:
577+ if (create_index_sql_statement .__str__ ()
578+ not in [sql .__str__ () for sql in self .deferred_sql ] + [statement [0 ].__str__ () for statement in post_actions ]
579+ ):
570580 self .execute (create_index_sql_statement )
571581
572582 # Type alteration on primary key? Then we need to alter the column
@@ -653,6 +663,7 @@ def _alter_field(self, model, old_field, new_field, old_type, new_type,
653663
654664 def _delete_indexes (self , model , old_field , new_field ):
655665 index_columns = []
666+ index_names = []
656667 if old_field .db_index and new_field .db_index :
657668 index_columns .append ([old_field .column ])
658669 elif old_field .null != new_field .null :
@@ -671,6 +682,7 @@ def _delete_indexes(self, model, old_field, new_field):
671682 index_names = self ._constraint_names (model , columns , index = True )
672683 for index_name in index_names :
673684 self .execute (self ._delete_constraint_sql (self .sql_delete_index , model , index_name ))
685+ return index_names
674686
675687 def _delete_unique_constraints (self , model , old_field , new_field , strict = False ):
676688 unique_columns = []
0 commit comments