[Answered ]-Django – UNIQUE constraint failed

2👍

class Product(models.Model):
    name = models.CharField(max_length=5)
    vat_rate = models.DecimalField(max_digits=5, decimal_places=2)
    amount = models.IntegerField(default=0, primary_key=True)

Amount is set as primary key, which means that the database will only allow 1 record per value of amount.

BUT, you’ve also set a default value of 0, so your DB can only create 1 record with amount = 0, whenever the amount value is not provided.

You must decide what you want. If the amount uniqueness matters, then remove default=0 and put null=True, blank=True, for example.

Leave a comment