0

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

3
  • You will have to change the duplicate values first or delete those entries. Commented Mar 25, 2021 at 10:15
  • how can i do that ? sorry I am new to this Commented Mar 25, 2021 at 10:20
  • Please add your models to the question. Commented Mar 25, 2021 at 10:22

1 Answer 1

2

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 !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.