I’ve created constraints by myself in migration because one of our servers have old postgres version and it works quite good, but every time I run makemigrations
django creates new migration for this app with this constraints, and then it fails because it’s already here. Here is the code of my hand-written constraints migration for understanding
from django.db import migrations, models, utils, transaction
def add_constraint_if_not_exists(
apps,
schema_editor,
condition,
fields,
constraint_name
):
MyModel = apps.get_model(...)
with transaction.atomic():
try:
constraint = models.UniqueConstraint(
condition=condition,
fields=fields,
name=constraint_name
)
schema_editor.add_constraint(MyModel, constraint)
except utils.ProgrammingError:
transaction.set_rollback(True)
def add_unique_..._constraint(apps, schema_editor):
condition = models.Q(('field', True))
fields = ('...', '...', '...')
add_constraint_if_not_exists(
apps,
schema_editor,
condition,
fields,
'unique_fields'
)
def add_unique_field_constraint(apps, schema_editor):
condition = models.Q(('field', False))
fields = ('field',)
add_constraint_if_not_exists(
apps,
schema_editor,
condition,
fields,
'unique_field'
)
class Migration(migrations.Migration):
dependencies = [
('app_name', '...'),
]
operations = [
migrations.RunPython(
add_unique_..._constraint, migrations.RunPython.noop),
migrations.RunPython(add_unique_field_constraint, migrations.RunPython.noop),
]
And when I’m running makemigrations
it creates this migration:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_name', '...'),
]
operations = [
migrations.AddConstraint(
model_name='mymodel',
constraint=models.UniqueConstraint(condition=models.Q(('field', True)), fields=('...', '...', '...'), name='unique_...'),
),
migrations.AddConstraint(
model_name='mymodel',
constraint=models.UniqueConstraint(condition=models.Q(('field', False)), fields=('field',), name='unique_field'),
),
]
What can I do to tell migration system that there is already constraints?