From 26c166c3b000ad829127046b1b107d9733a6a2ef Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Fri, 25 Feb 2022 22:01:27 +0100 Subject: [PATCH] Added test for removing through model from ManyToManyField. --- tests/schema/tests.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/schema/tests.py b/tests/schema/tests.py index 37f2946006..b47c720064 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -1894,6 +1894,41 @@ class SchemaTests(TransactionTestCase): def test_m2m_create_through_inherited(self): self._test_m2m_create_through(InheritedManyToManyField) + def test_m2m_through_remove(self): + class LocalAuthorNoteThrough(Model): + book = ForeignKey("schema.Author", CASCADE) + tag = ForeignKey("self", CASCADE) + + class Meta: + app_label = "schema" + apps = new_apps + + class LocalNoteWithM2MThrough(Model): + authors = ManyToManyField("schema.Author", through=LocalAuthorNoteThrough) + + class Meta: + app_label = "schema" + apps = new_apps + + self.local_models = [LocalAuthorNoteThrough, LocalNoteWithM2MThrough] + # Create the tables. + with connection.schema_editor() as editor: + editor.create_model(Author) + editor.create_model(LocalAuthorNoteThrough) + editor.create_model(LocalNoteWithM2MThrough) + # Remove the through parameter. + old_field = LocalNoteWithM2MThrough._meta.get_field("authors") + new_field = ManyToManyField("Author") + new_field.set_attributes_from_name("authors") + msg = ( + f"Cannot alter field {old_field} into {new_field} - they are not " + f"compatible types (you cannot alter to or from M2M fields, or add or " + f"remove through= on M2M fields)" + ) + with connection.schema_editor() as editor: + with self.assertRaisesMessage(ValueError, msg): + editor.alter_field(LocalNoteWithM2MThrough, old_field, new_field) + def _test_m2m(self, M2MFieldClass): """ Tests adding/removing M2M fields on models