Skip to content

Commit 44af893

Browse files
committed
add unique creation/deletion support to SchemaEditor.alter_field()
1 parent 70902b2 commit 44af893

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

django_mongodb/features.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
7272
"backends.tests.ThreadTests.test_pass_connection_between_threads",
7373
"backends.tests.ThreadTests.test_closing_non_shared_connections",
7474
"backends.tests.ThreadTests.test_default_connection_thread_local",
75-
# AlterField
76-
"schema.tests.SchemaTests.test_alter_field_fk_to_o2o",
77-
"schema.tests.SchemaTests.test_alter_field_o2o_to_fk",
78-
# AlterField (unique)
79-
"schema.tests.SchemaTests.test_indexes",
80-
"schema.tests.SchemaTests.test_unique",
8175
}
8276
# $bitAnd, #bitOr, and $bitXor are new in MongoDB 6.3.
8377
_django_test_expected_failures_bitwise = {

django_mongodb/schema.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,9 @@ def _alter_field(
8989
strict=False,
9090
):
9191
collection = self.get_collection(model._meta.db_table)
92+
# Has unique been removed?
93+
if self._field_should_have_unique(old_field) and not self._field_should_have_unique(new_field):
94+
self._remove_field_unique(model, old_field, strict)
9295
# Removed an index?
9396
old_field_indexed = self._field_should_be_indexed(model, old_field)
9497
new_field_indexed = self._field_should_be_indexed(model, new_field)
@@ -101,6 +104,11 @@ def _alter_field(
101104
if old_field_indexed and new_field_indexed:
102105
self._remove_field_index(model, old_field)
103106
self._add_field_index(model, new_field)
107+
# Move unique to the new field, if needed.
108+
if self._field_should_have_unique(old_field) and self._field_should_have_unique(new_field):
109+
if not old_field.primary_key:
110+
self._remove_field_unique(model, old_field, strict)
111+
self._add_field_unique(model, new_field)
104112
# Replace NULL with the field default if the field and was changed from
105113
# NULL to NOT NULL.
106114
if new_field.has_default() and old_field.null and not new_field.null:
@@ -110,6 +118,9 @@ def _alter_field(
110118
# Added an index?
111119
if not old_field_indexed and new_field_indexed:
112120
self._add_field_index(model, new_field)
121+
# Added a unique?
122+
if self._unique_should_be_added(old_field, new_field):
123+
self._add_field_unique(model, new_field)
113124

114125
def remove_field(self, model, field):
115126
# Remove implicit M2M tables.

0 commit comments

Comments
 (0)