From 3d9040a50b160f8b4bb580e09f4120d4979fe29e Mon Sep 17 00:00:00 2001 From: Jordan Bae Date: Mon, 26 Jul 2021 23:56:05 +0900 Subject: [PATCH] Refs #32743 -- Fixed recreation of foreign key constraints when altering type of referenced primary key with MTI. Follow up to 325d7710ce9f6155bb55610ad6b4580d31263557. --- AUTHORS | 1 + django/db/backends/base/schema.py | 4 ++-- tests/migrations/test_operations.py | 22 ++++++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/AUTHORS b/AUTHORS index 783a52298fc..33e1bdc91a3 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 47fdae8fd4f..6af166717c4 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 84f1b89ba53..6d016a2a25b 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):