Skip to content

Commit 1c0706b

Browse files
committed
add index creation/deletion support to SchemaEditor.alter_field()
1 parent 4fd0895 commit 1c0706b

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

django_mongodb/features.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,16 +72,12 @@ class DatabaseFeatures(BaseDatabaseFeatures):
7272
# AddField
7373
"schema.tests.SchemaTests.test_add_unique_charfield",
7474
# AlterField
75-
"schema.tests.SchemaTests.test_alter_field_add_index_to_integerfield",
7675
"schema.tests.SchemaTests.test_alter_field_fk_to_o2o",
7776
"schema.tests.SchemaTests.test_alter_field_o2o_keeps_unique",
7877
"schema.tests.SchemaTests.test_alter_field_o2o_to_fk",
7978
"schema.tests.SchemaTests.test_alter_int_pk_to_int_unique",
80-
# AlterField (db_index)
81-
"schema.tests.SchemaTests.test_alter_renames_index",
82-
"schema.tests.SchemaTests.test_indexes",
83-
"schema.tests.SchemaTests.test_remove_db_index_doesnt_remove_custom_indexes",
8479
# AlterField (unique)
80+
"schema.tests.SchemaTests.test_indexes",
8581
"schema.tests.SchemaTests.test_unique",
8682
"schema.tests.SchemaTests.test_unique_and_reverse_m2m",
8783
# alter_unique_together

django_mongodb/schema.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,15 +78,27 @@ def _alter_field(
7878
strict=False,
7979
):
8080
collection = self.get_collection(model._meta.db_table)
81+
# Removed an index?
82+
old_field_indexed = self._field_should_be_indexed(model, old_field)
83+
new_field_indexed = self._field_should_be_indexed(model, new_field)
84+
if old_field_indexed and not new_field_indexed:
85+
self._remove_field_index(model, old_field)
8186
# Have they renamed the column?
8287
if old_field.column != new_field.column:
8388
collection.update_many({}, {"$rename": {old_field.column: new_field.column}})
89+
# Move index to the new field, if needed.
90+
if old_field_indexed and new_field_indexed:
91+
self._remove_field_index(model, old_field)
92+
self._add_field_index(model, new_field)
8493
# Replace NULL with the field default if the field and was changed from
8594
# NULL to NOT NULL.
8695
if new_field.has_default() and old_field.null and not new_field.null:
8796
column = new_field.column
8897
default = self.effective_default(new_field)
8998
collection.update_many({column: {"$eq": None}}, [{"$set": {column: default}}])
99+
# Added an index?
100+
if not old_field_indexed and new_field_indexed:
101+
self._add_field_index(model, new_field)
90102

91103
def remove_field(self, model, field):
92104
# Remove implicit M2M tables.

0 commit comments

Comments
 (0)