Skip to content

Commit d3a106c

Browse files
committed
add unique creation/deletion support to SchemaEditor.alter_field()
1 parent 39e6a8e commit d3a106c

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

django_mongodb/features.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
7373
"backends.tests.ThreadTests.test_pass_connection_between_threads",
7474
"backends.tests.ThreadTests.test_closing_non_shared_connections",
7575
"backends.tests.ThreadTests.test_default_connection_thread_local",
76-
# AlterField
77-
"schema.tests.SchemaTests.test_alter_field_fk_to_o2o",
78-
"schema.tests.SchemaTests.test_alter_field_o2o_to_fk",
79-
# AlterField (unique)
80-
"schema.tests.SchemaTests.test_indexes",
81-
"schema.tests.SchemaTests.test_unique",
8276
# Column default values aren't handled when a field raises
8377
# EmptyResultSet: https://github.com/mongodb-labs/django-mongodb/issues/155
8478
"annotations.tests.NonAggregateAnnotationTestCase.test_empty_queryset_annotation",

django_mongodb/schema.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,11 @@ def _alter_field(
8888
strict=False,
8989
):
9090
collection = self.get_collection(model._meta.db_table)
91+
# Has unique been removed?
92+
old_field_unique = self._field_should_have_unique(old_field)
93+
new_field_unique = self._field_should_have_unique(new_field)
94+
if old_field_unique and not new_field_unique:
95+
self._remove_field_unique(model, old_field)
9196
# Removed an index?
9297
old_field_indexed = self._field_should_be_indexed(model, old_field)
9398
new_field_indexed = self._field_should_be_indexed(model, new_field)
@@ -100,6 +105,10 @@ def _alter_field(
100105
if old_field_indexed and new_field_indexed:
101106
self._remove_field_index(model, old_field)
102107
self._add_field_index(model, new_field)
108+
# Move unique to the new field, if needed.
109+
if old_field_unique and new_field_unique:
110+
self._remove_field_unique(model, old_field)
111+
self._add_field_unique(model, new_field)
103112
# Replace NULL with the field default if the field and was changed from
104113
# NULL to NOT NULL.
105114
if new_field.has_default() and old_field.null and not new_field.null:
@@ -109,6 +118,9 @@ def _alter_field(
109118
# Added an index?
110119
if not old_field_indexed and new_field_indexed:
111120
self._add_field_index(model, new_field)
121+
# Added a unique?
122+
if not old_field_unique and new_field_unique:
123+
self._add_field_unique(model, new_field)
112124

113125
def remove_field(self, model, field):
114126
# Remove implicit M2M tables.

0 commit comments

Comments
 (0)