0
votes

I got following user table with same uuid . I want this uuid to be unique . but while changing the uuid from my user model with unique=True and editable=False While executing migrate command , I am getting "psycopg2.errors.UniqueViolation: could not create unique index" error with Key (hnid)=(8c0bc4a2-165a-47d5-8084-8b87600c7fe8) is duplicated.

my models.py

hnid = models.UUIDField("HNID", default=uuid.uuid4, blank=True, null=True, unique=True,editable=False)

Note: I am using postgres How can I solve this issue enter image description here

1
You will have to change the duplicate values first or delete those entries.Abdul Aziz Barkat
how can i do that ? sorry I am new to thisMitesh
Please add your models to the question.Abdul Aziz Barkat

1 Answers

0
votes

Be careful with your definition of hnid. You can use directly primary_key=True.

hnid = models.UUIDField(
        primary_key=True,
        default=uuid_lib.uuid4,
        editable=False,
    )

primary_key=True implies null=False and unique=True and is readonly. Only one primary key is allowed on an object according to the doc. blank=True is not a good idea : you do not want to have a blank primary key on your object. Plus, it would not work with unique=True.

About the migration, Django gives a good example on their documention : https://docs.djangoproject.com/en/3.1/howto/writing-migrations/#migrations-that-add-unique-fields And it works well !