Skip to content

Commit 39e6a8e

Browse files
committed
add support for Meta.unique_together
1 parent 3649ef5 commit 39e6a8e

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

django_mongodb/features.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
7979
# AlterField (unique)
8080
"schema.tests.SchemaTests.test_indexes",
8181
"schema.tests.SchemaTests.test_unique",
82-
# alter_unique_together
83-
"migrations.test_operations.OperationTests.test_alter_unique_together",
84-
"schema.tests.SchemaTests.test_unique_together",
8582
# Column default values aren't handled when a field raises
8683
# EmptyResultSet: https://github.com/mongodb-labs/django-mongodb/issues/155
8784
"annotations.tests.NonAggregateAnnotationTestCase.test_empty_queryset_annotation",

django_mongodb/schema.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def create_model(self, model):
3030
def _create_model_indexes(self, model):
3131
"""
3232
Create all indexes (field indexes & uniques, Meta.index_together,
33-
Meta.constraints, Meta.indexes) for the specified model.
33+
Meta.unique_together, Meta.constraints, Meta.indexes) for the model.
3434
"""
3535
if not model._meta.managed or model._meta.proxy or model._meta.swapped:
3636
return
@@ -43,6 +43,9 @@ def _create_model_indexes(self, model):
4343
# Meta.index_together (RemovedInDjango51Warning)
4444
for field_names in model._meta.index_together:
4545
self._add_composed_index(model, field_names)
46+
# Meta.unique_together
47+
if model._meta.unique_together:
48+
self.alter_unique_together(model, [], model._meta.unique_together)
4649
# Meta.constraints
4750
for constraint in model._meta.constraints:
4851
self.add_constraint(model, constraint)
@@ -131,7 +134,21 @@ def alter_index_together(self, model, old_index_together, new_index_together):
131134
self._add_composed_index(model, field_names)
132135

133136
def alter_unique_together(self, model, old_unique_together, new_unique_together):
134-
pass
137+
olds = {tuple(fields) for fields in old_unique_together}
138+
news = {tuple(fields) for fields in new_unique_together}
139+
# Deleted uniques
140+
for field_names in olds.difference(news):
141+
self._remove_composed_index(
142+
model,
143+
field_names,
144+
{"unique": True, "primary_key": False},
145+
)
146+
# Created uniques
147+
for field_names in news.difference(olds):
148+
columns = [model._meta.get_field(field).column for field in field_names]
149+
name = str(self._unique_constraint_name(model._meta.db_table, columns))
150+
constraint = UniqueConstraint(fields=field_names, name=name)
151+
self.add_constraint(model, constraint)
135152

136153
def add_index(self, model, index, field=None, unique=False):
137154
if index.contains_expressions:

0 commit comments

Comments
 (0)