Django Check for duplicates with 2 model fields

Viewed 102

I have a model that looks like this:

class UssdCode(models.Model):
    title = models.CharField(max_length=100)
    code = models.CharField(max_length=100)
    product = models.CharField(max_length=100)

How can I get the admin to alert me and reject my entry when I try to add a new object that has the same 'code' and 'product' as an object already in the database.

1 Answers

You make it unique together. Since , you can use the UniqueConstraint [Django-doc] of the Django Constraint framework [Django-doc] for that:

# since Django-2.2

class UssdCode(models.Model):
    title = models.CharField(max_length=100)
    code = models.CharField(max_length=100)
    product = models.CharField(max_length=100)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['code', 'product'], name='code_product')
        ]

Prior to , you can use the unique_together meta option [Django-doc]:

# before Django-2.2 (still works on Django-3.0)

class UssdCode(models.Model):
    title = models.CharField(max_length=100)
    code = models.CharField(max_length=100)
    product = models.CharField(max_length=100)

    class Meta:
        unique_together = [['code', 'product']]
Related