I have a Django model which is using the Django unique_together
constraint.
class MyModel(models.Model):
field_1
field_2
class Meta:
unique_together = ("field_1", "field_2")
At some point after this constraint was created on MyModel
, a migration was created to rename MyModel
to MyCoolModel
.
Some time after that the renaming migration was squashed into the original migration that created the constraint.
Now where I previously had 2 migrations.
create_my_model_with_constraint
rename_to_my_cool_model
I only have one: create_my_cool_model_with_constraint
Later I want to adapt the existing unique_together
constraint in line with the following model change:
class MyCoolModel(models.Model):
field_1
field_2
field_3
class Meta:
unique_together = ("field_1", "field_2", "field_3")
I create a migration for this change which has the following SQL output:
BEGIN;
ALTER TABLE "models_mycoolmodel"
DROP CONSTRAINT "models_mycoolmodel_field_1_field_2_ca69545b_uniq";
ALTER TABLE "models_mycoolmodel"
ADD CONSTRAINT "models_mycoolmodel_field_1_field_2_field_3_aedebc1b_uniq"
UNIQUE ("field_1", "field_2", "field_3");
COMMIT;
This change applies fine to my local db (which has been created since the migration squashing event), but when deployed to production the migration errors because the constraint "models_mycoolmodel_field_1_field_2_ca69545b_uniq"
does not exist.
Instead the same constraint is called models_mymodel_field_1_field_2_7d93nd0q_uniq
.
My question is what has caused the differing constraint names between my local env and production?
My suspicion is that by squashing the table name change migration into the initial migration that created the unique_together
constraint, this changed the name Django saw for the table at the point of initially applying the constraint and generating the name for it. However, I'm not 100% certain of this so am hoping someone can confirm this for me.
Would the two bits of migration code below be expected to yield constraints with different names?
Original migration:
migrations.CreateModel(
name="MyModel",
field=[("field_1"), ("field_2")],
options={"unique_together": ("field_1", "field_2")}
)
Squashed migration:
migrations.CreateModel(
name="MyModel",
field=[("field_1"), ("field_2")],
options={"unique_together": ("field_1", "field_2")}
)
migrations.RenameModel(old_name="MyModel", new_name="MyCoolModel")
As a note the migrations are both atomic.
question from:
https://stackoverflow.com/questions/65899224/how-does-django-generate-constraint-names-in-migrations