diff --git a/AUTHORS b/AUTHORS index 783a52298f..33e1bdc91a 100644 --- a/AUTHORS +++ b/AUTHORS @@ -483,6 +483,7 @@ answer newbie questions, and generally made Django that much better: Jonathan Daugherty (cygnus) Jonathan Feignberg Jonathan Slenders + Jordan Bae Jordan Dimov Jordi J. Tablada Jorge Bastida diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py index 47fdae8fd4..6af166717c 100644 --- a/django/db/backends/base/schema.py +++ b/django/db/backends/base/schema.py @@ -849,8 +849,8 @@ class BaseDatabaseSchemaEditor: self.execute(self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s")) # Rebuild FKs that pointed to us if we previously had to drop them if drop_foreign_keys: - for rel in new_field.model._meta.related_objects: - if _is_relevant_relation(rel, new_field) and rel.field.db_constraint: + for _, rel in rels_to_update: + if rel.field.db_constraint: self.execute(self._create_fk_sql(rel.related_model, rel.field, "_fk")) # Does it have check constraints we need to add? if old_db_params['check'] != new_db_params['check'] and new_db_params['check']: diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py index 84f1b89ba5..6d016a2a25 100644 --- a/tests/migrations/test_operations.py +++ b/tests/migrations/test_operations.py @@ -1551,10 +1551,32 @@ class OperationTests(OperationTestBase): with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertIdTypeEqualsMTIFkType() + if connection.features.supports_foreign_keys: + self.assertFKExists( + f'{app_label}_shetlandpony', + ['pony_ptr_id'], + (f'{app_label}_pony', 'id'), + ) + self.assertFKExists( + f'{app_label}_shetlandrider', + ['pony_id'], + (f'{app_label}_shetlandpony', 'pony_ptr_id'), + ) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertIdTypeEqualsMTIFkType() + if connection.features.supports_foreign_keys: + self.assertFKExists( + f'{app_label}_shetlandpony', + ['pony_ptr_id'], + (f'{app_label}_pony', 'id'), + ) + self.assertFKExists( + f'{app_label}_shetlandrider', + ['pony_id'], + (f'{app_label}_shetlandpony', 'pony_ptr_id'), + ) @skipUnlessDBFeature('supports_foreign_keys') def test_alter_field_reloads_state_on_fk_with_to_field_target_type_change(self):