[Solved]-How to properly make migrations when adding a new unique field

5👍

Maybe it’s too late but maybe it could work for someone else

You can do this in one migration via using migrations.RunSQL method

For your example code after you added the new field to your model and run the python manage.py makemigrations command (here if you have existing rows in your table command wants to choice default value you can choice “Provide a one-off default now” option and give some string value it is not important because actually we did not use it) then go to migration file and change operations part with this (Note i use postgresql you can change SQL for your database)

operations = [
        migrations.RunSQL(
        'ALTER TABLE "agency" ADD COLUMN "email" varchar(254) NULL;ALTER TABLE "agency" ALTER COLUMN "email" DROP DEFAULT;COMMIT;',
        ),
        migrations.RunSQL(
        "UPDATE agency SET email= Concat(country_code, '@example.fr');COMMIT;",
        ),
        migrations.RunSQL(
        'ALTER TABLE "agency" ALTER COLUMN "email" SET NOT NULL;ALTER TABLE "agency" ADD CONSTRAINT "agency_email_b551ad2a_uniq" UNIQUE ("email");ALTER TABLE "agency" ALTER COLUMN "email" DROP DEFAULT;CREATE INDEX "agency_email_b551ad2a_like" ON "agency" ("email" varchar_pattern_ops);COMMIT;'
        )
    ]

then run “python manage.py migrate” command
that is it.

Leave a comment