Skip to content

Commit

Permalink
AddField support
Browse files Browse the repository at this point in the history
  • Loading branch information
timgraham committed Dec 30, 2024
1 parent 9b6b6ba commit a52c33e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
6 changes: 6 additions & 0 deletions django_mongodb/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
32 changes: 31 additions & 1 deletion tests/schema_/test_embedded_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)

0 comments on commit a52c33e

Please sign in to comment.