1

Okay so here is the behaviour explained.

1. I create a new Post object via admin panel.

2. Object is saved.

3. Create one more Post object after that.

4. Get error

django.db.utils.IntegrityError: duplicate key value violates unique constraint "lp_post_pkey" DETAIL: Key (id)=(5de7b062-14b2-42ef-a9ee-95bbb17ccf3b) already exists.

I have read duplicate key value violates unique constraint in django .

The problem is probably the same that my primary key sequence in the table i'm working with has become out of sync. And the solution to that was to set the current Primary Key from maximum +1.

But i'm using uuid's for my primary key, that probably isn't the solution for me.

So, how can i sync my primary keys if the problem really is at that?

Btw, when i reset the local server i can repeat the steps from 1-4.

As well, i've noticed when i'm doing a manage.py makemigrations even when i have nothing to migrate, my uuid fields keep altering to new ones. Can the problem be somehow related?

models.py

class SubscriberModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4(), unique=True, editable=False)
    email = models.EmailField()
    subscribed = models.DateTimeField(default=timezone.now())
    ip_addr = models.CharField(null=False, max_length=250, default="")
    objects = models.Manager()

    def __str__(self):
        return "{%s}/EMAIL\{%s}/\Subscribed On/\{%s}/\From this IP" % \
               (self.email, self.subscribed, self.ip_addr)

    class Meta:
        unique_together = ('email', 'ip_addr')


class ContactUsModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4(), unique=True, editable=False)
    name = models.CharField(max_length=150, null=False)
    email = models.EmailField()
    body = models.TextField()
    ip_addr = models.CharField(null=False, max_length=250, default="")
    date = models.DateTimeField(default=timezone.now())
    objects = models.Manager()

    def __str__(self):
        return 'mail from {%s} | at {%s}' % (self.email, self.date)

    class Meta:
        unique_together = ('email', 'ip_addr')


def save_image(title, filename):
    return '{%s}-{%s}' % (title, filename)


class Post(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4(), unique=True, editable=False)
    title = models.CharField(max_length=250)
    body = models.TextField()
    main_image = models.ImageField(null=False, upload_to=save_image)
    second_image = models.ImageField(blank=True, default="")
    third_image = models.ImageField(blank=True, default="")
    fourth_image = models.ImageField(blank=True, default="")
    fifth_image = models.ImageField(blank=True, default="")
    created_at = models.DateTimeField(default=timezone.now())

    # get url

    def slug(self):
        return slugify(self.title)

    def get_absolute_url(self):
        return reverse('lp:post_detail', kwargs={'slug': self.slug(),
                                                 'pk': self.pk})

    def __str__(self):
        return '%s' % self.title

    class Meta:
        ordering = ['-created_at']

Full traceback

Traceback (most recent call last): File "/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "lp_post_pkey" DETAIL: Key (id)=(5de7b062-14b2-42ef-a9ee-95bbb17ccf3b) already exists.

My 2 last migrations

class Migration(migrations.Migration):

    dependencies = [
        ('lp', '0008_auto_20191221_2016'),
    ]

    operations = [
        migrations.AlterField(
            model_name='contactusmodel',
            name='date',
            field=models.DateTimeField(default=datetime.datetime(2019, 12, 21, 20, 17, 10, 770047, tzinfo=utc)),
        ),
        migrations.AlterField(
            model_name='contactusmodel',
            name='id',
            field=models.UUIDField(default=uuid.UUID('37e52230-3c82-45eb-bbb9-aeb432b12247'), editable=False, primary_key=True, serialize=False, unique=True),
        ),
        migrations.AlterField(
            model_name='post',
            name='created_at',
            field=models.DateTimeField(default=datetime.datetime(2019, 12, 21, 20, 17, 10, 770612, tzinfo=utc)),
        ),
        migrations.AlterField(
            model_name='post',
            name='id',
            field=models.UUIDField(default=uuid.UUID('f4e05be4-2722-47b2-b636-232079114157'), editable=False, primary_key=True, serialize=False, unique=True),
        ),
        migrations.AlterField(
            model_name='subscribermodel',
            name='id',
            field=models.UUIDField(default=uuid.UUID('61b77cb5-5f33-4b8b-b235-83d3b10cc989'), editable=False, primary_key=True, serialize=False, unique=True),
        ),
        migrations.AlterField(
            model_name='subscribermodel',
            name='subscribed',
            field=models.DateTimeField(default=datetime.datetime(2019, 12, 21, 20, 17, 10, 741394, tzinfo=utc)),
        ),
    ]


class Migration(migrations.Migration):

    dependencies = [
        ('lp', '0007_auto_20191221_2004'),
    ]

    operations = [
        migrations.AlterField(
            model_name='contactusmodel',
            name='date',
            field=models.DateTimeField(default=datetime.datetime(2019, 12, 21, 20, 16, 18, 987126, tzinfo=utc)),
        ),
        migrations.AlterField(
            model_name='contactusmodel',
            name='id',
            field=models.UUIDField(default=uuid.UUID('fabeec4c-bdd0-443a-81e9-2ea0ba8c8f4b'), editable=False, primary_key=True, serialize=False, unique=True),
        ),
        migrations.AlterField(
            model_name='post',
            name='created_at',
            field=models.DateTimeField(verbose_name=datetime.datetime(2019, 12, 21, 20, 16, 18, 987702, tzinfo=utc)),
        ),
        migrations.AlterField(
            model_name='post',
            name='id',
            field=models.UUIDField(default=uuid.UUID('aafc7ac3-f48b-4a74-a9cd-2af3a8d3fcae'), editable=False, primary_key=True, serialize=False, unique=True),
        ),
        migrations.AlterField(
            model_name='subscribermodel',
            name='id',
            field=models.UUIDField(default=uuid.UUID('b9c2a42c-3265-4a13-af48-ff5db4f38d30'), editable=False, primary_key=True, serialize=False, unique=True),
        ),
        migrations.AlterField(
            model_name='subscribermodel',
            name='subscribed',
            field=models.DateTimeField(default=datetime.datetime(2019, 12, 21, 20, 16, 18, 958998, tzinfo=utc)),
        ),
    ]
h1dd3n
  • 292
  • 1
  • 12

1 Answers1

2

Your problem is you are setting the default to uuid.uuid4(). This will create one id when the application first starts, then try to use the same one for every post.

The solution is to use default=uuid.uuid4 without the parenthesis. This will automatically execute the function for every record, generating a new uuid.

mousetail
  • 7,009
  • 4
  • 25
  • 45