Reputation: 649
Django 2.2 postgres
I added uuid to my existing django model , generated and applied a migration for the table that already had records in it:
migrations.AddField(
model_name='<mymodel>',
name='uuid',
field=models.UUIDField(default=uuid.uuid4, editable=False),
),
The field got added fine, however all the existing records got the same value inserted in the uuid field. How do I make default=uuid.uuid4 to generate a new uuid value for each existing records?
Thanks
Upvotes: 2
Views: 4301
Reputation: 649
Turned out you can't do it through normal django migration procedure (makemigrations / migrate). You have to do it as a custom 3 migrations, the procedure is described here: https://docs.djangoproject.com/en/2.2/howto/writing-migrations/#migrations-that-add-unique-fields . Thanks to Muhammad Hashir Hassan for pointing me to the discussion on the subject where I found this link to the documentaipon.
Upvotes: 2
Reputation: 400
Add Unique constraint for unique id for every model
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
Then your migrations will look like this
migrations.AddField(
model_name=<<model_name>>,
name='uuid',
field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True),
),
Given that you have added import uuid.
When you run migrations now it will show error that your previous records contain same values which conflicts with the unique constriant so you might be looking forward to remove or override previous records to resolve this possible conflict.
Upvotes: 2