Prometheus
Prometheus

Reputation: 33655

Django key violates unique constraint

I have a strange issue where the same PK is being generated giving me the error:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "Comment_pkey"
DETAIL:  Key (id)=(uxlt72XrRu-fm260qHo9Zg) already exists.

This is my model:

class Comment(models.Model):

    id = models.CharField(primary_key=True, max_length=28, unique=True,
                          default="make_id()", editable=False)
    description = models.TextField(max_length=255)

Function to generate ID:

def make_id():
    return base64.b64encode(uuid.uuid4().bytes).decode("utf-8")

How I get the error:

c = Comment.objects.create(description="test") < ==== works

c2 = Comment.objects.create(description="test2") < === violates unique constraint

So why is my model not generating a new ID each time? The same thing happens in tests not just shell.

Upvotes: 1

Views: 765

Answers (1)

Adrian Ghiuta
Adrian Ghiuta

Reputation: 1619

Correct usage of the default param is: default=make_id. So, the field line would be:

id = models.CharField(primary_key=True, max_length=28, unique=True,
                      default=make_id, editable=False)

Upvotes: 5

Related Questions