From a52c33e4bac96ebc0b869dbbb9697590e33268fb Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Mon, 25 Nov 2024 20:40:18 -0500 Subject: [PATCH] AddField support --- django_mongodb/schema.py | 6 ++++++ tests/schema_/test_embedded_model.py | 32 +++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/django_mongodb/schema.py b/django_mongodb/schema.py index dab1a1fc..c351d2a0 100644 --- a/django_mongodb/schema.py +++ b/django_mongodb/schema.py @@ -92,6 +92,12 @@ def add_field(self, model, field): self.get_collection(model._meta.db_table).update_many( {}, [{"$set": {column: self.effective_default(field)}}] ) + if isinstance(field, EmbeddedModelField): + new_path = f"{field.column}." + self._create_model_indexes( + field.embedded_model, parent_model=model, column_prefix=new_path + ) + # Add an index or unique, if required. if self._field_should_be_indexed(model, field): self._add_field_index(model, field) diff --git a/tests/schema_/test_embedded_model.py b/tests/schema_/test_embedded_model.py index ba9b9788..430ec943 100644 --- a/tests/schema_/test_embedded_model.py +++ b/tests/schema_/test_embedded_model.py @@ -163,7 +163,7 @@ def assertTableExists(self, model): def assertTableNotExists(self, model): self.assertNotIn(model._meta.db_table, connection.introspection.table_names()) - # Tests + # SchemaEditor.create_model() tests def test_db_index(self): """Field(db_index=True) on an embedded model.""" with connection.schema_editor() as editor: @@ -391,3 +391,33 @@ class Meta: ) editor.delete_model(Author) self.assertTableNotExists(Author) + + # SchemaEditor.add_field() tests + @isolate_apps("schema_") + def test_add_field_db_index(self): + """AddField + EmbeddedModelField""" + + class Book(models.Model): + name = models.CharField(max_length=100) + + class Meta: + app_label = "schema_" + + new_field = EmbeddedModelField(Author) + new_field.set_attributes_from_name("author") + + with connection.schema_editor() as editor: + # Create the table amd add the field. + editor.create_model(Book) + editor.add_field(Book, new_field) + # Embedded indexes are created. + self.assertEqual( + self.get_constraints_for_columns(Book, ["author.age"]), + ["schema__book_author.age_dc08100b"], + ) + self.assertEqual( + self.get_constraints_for_columns(Book, ["author.address.zip_code"]), + ["schema__book_author.address.zip_code_7b9a9307"], + ) + editor.delete_model(Book) + self.assertTableNotExists(Author)