Skip to content

Commit 84a23d7

Browse files
committed
implement SchemaEditor.alter_index_together()
1 parent 66837ea commit 84a23d7

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

django_mongodb/features.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
9191
# AlterField (unique)
9292
"schema.tests.SchemaTests.test_unique",
9393
"schema.tests.SchemaTests.test_unique_and_reverse_m2m",
94-
# alter_index_together
95-
"migrations.test_operations.OperationTests.test_alter_index_together",
96-
"schema.tests.SchemaTests.test_index_together",
9794
# alter_unique_together
9895
"migrations.test_operations.OperationTests.test_alter_unique_together",
9996
"schema.tests.SchemaTests.test_unique_together",

django_mongodb/schema.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,14 @@ def remove_field(self, model, field):
8686
self.connection.database[model._meta.db_table].update_many({}, {"$unset": {column: ""}})
8787

8888
def alter_index_together(self, model, old_index_together, new_index_together):
89-
pass
89+
olds = {tuple(fields) for fields in old_index_together}
90+
news = {tuple(fields) for fields in new_index_together}
91+
# Deleted indexes
92+
for field_names in olds.difference(news):
93+
self._remove_composed_index(model, field_names, {"index": True, "unique": False})
94+
# Created indexes
95+
for field_names in news.difference(olds):
96+
self._add_composed_index(model, field_names)
9097

9198
def alter_unique_together(self, model, old_unique_together, new_unique_together):
9299
pass
@@ -125,6 +132,30 @@ def remove_index(self, model, index):
125132
return
126133
self.connection.database[model._meta.db_table].drop_index(index.name)
127134

135+
def _remove_composed_index(self, model, field_names, constraint_kwargs):
136+
"""
137+
Remove the index on the given list of field_names created by
138+
index/unique_together, depending on the constraint_kwargs.
139+
"""
140+
meta_constraint_names = {constraint.name for constraint in model._meta.constraints}
141+
meta_index_names = {constraint.name for constraint in model._meta.indexes}
142+
columns = [model._meta.get_field(field).column for field in field_names]
143+
constraint_names = self._constraint_names(
144+
model,
145+
columns,
146+
exclude=meta_constraint_names | meta_index_names,
147+
**constraint_kwargs,
148+
)
149+
if len(constraint_names) != 1:
150+
num_found = len(constraint_names)
151+
columns_str = ", ".join(columns)
152+
raise ValueError(
153+
f"Found wrong number ({num_found}) of constraints for "
154+
f"{model._meta.db_table}({columns_str})."
155+
)
156+
collection = self.connection.database[model._meta.db_table]
157+
collection.drop_index(constraint_names[0])
158+
128159
def add_constraint(self, model, constraint):
129160
pass
130161

0 commit comments

Comments
 (0)