Django model add uuid

Viewed 2374

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

2 Answers

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.

Related