Skip to content

Commit 81ea2fd

Browse files
committed
implement SchemaEditor.alter_index_together()
1 parent bf70cf1 commit 81ea2fd

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
@@ -84,9 +84,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
8484
# AlterField (unique)
8585
"schema.tests.SchemaTests.test_unique",
8686
"schema.tests.SchemaTests.test_unique_and_reverse_m2m",
87-
# alter_index_together
88-
"migrations.test_operations.OperationTests.test_alter_index_together",
89-
"schema.tests.SchemaTests.test_index_together",
9087
# alter_unique_together
9188
"migrations.test_operations.OperationTests.test_alter_unique_together",
9289
"schema.tests.SchemaTests.test_unique_together",

django_mongodb/schema.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,14 @@ def remove_field(self, model, field):
8888
self._remove_field_index(model, field)
8989

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

93100
def alter_unique_together(self, model, old_unique_together, new_unique_together):
94101
pass
@@ -124,6 +131,30 @@ def remove_index(self, model, index):
124131
return
125132
self.connection.database[model._meta.db_table].drop_index(index.name)
126133

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

0 commit comments

Comments
 (0)