@@ -89,9 +89,15 @@ def _alter_field(self, model, old_field, new_field, old_type, new_type,
8989 ))
9090 for constraint_name in constraint_names :
9191 self .execute (self ._delete_constraint_sql (self .sql_delete_unique , model , constraint_name ))
92- # Drop incoming FK constraints if we're a primary key and things are going
93- # to change.
94- if old_field .primary_key and new_field .primary_key and old_type != new_type :
92+ # Drop incoming FK constraints if the field is a primary key or unique,
93+ # which might be a to_field target, and things are going to change.
94+ drop_foreign_keys = (
95+ (
96+ (old_field .primary_key and new_field .primary_key ) or
97+ (old_field .unique and new_field .unique )
98+ ) and old_type != new_type
99+ )
100+ if drop_foreign_keys :
95101 # '_meta.related_field' also contains M2M reverse fields, these
96102 # will be filtered out
97103 for _old_rel , new_rel in _related_non_m2m_objects (old_field , new_field ):
@@ -348,7 +354,7 @@ def _alter_field(self, model, old_field, new_field, old_type, new_type,
348354 new_field .db_constraint ):
349355 self .execute (self ._create_fk_sql (model , new_field , "_fk_%(to_table)s_%(to_column)s" ))
350356 # Rebuild FKs that pointed to us if we previously had to drop them
351- if old_field . primary_key and new_field . primary_key and old_type != new_type :
357+ if drop_foreign_keys :
352358 for rel in new_field .model ._meta .related_objects :
353359 if not rel .many_to_many and rel .field .db_constraint :
354360 self .execute (self ._create_fk_sql (rel .related_model , rel .field , "_fk" ))
0 commit comments