Search code examples
pythondjangopostgresqldjango-2.2

django unique object (not unique field)?


how to make a unique object (not unique per field)

e.g:

name : honda

category : car

success

name : honda

category : bike

success

name : honda

category : bike

failed coz all field have same value to another object

if i use unique at the field, the second case will be failed, coz honda (name) already created

my code :

class Category(models.Model):
    name = models.CharField(max_length=127,unique=True)

    def __str__(self):
        return self.name


class Brand(models.Model):
    name = models.CharField(max_length=127,unique=True)
    category = models.ForeignKey(Category,on_delete=models.CASCADE)         

    def __str__(self):
        return self.name

Solution

  • Django provides a Meta option called unique together which seems to satisfy this use case:

    class Brand(models.Model):
        name = models.CharField(max_length=127)
        category = models.ForeignKey(Category, on_delete=models.CASCADE)
    
        class Meta:
            unique_together = [[“name”, “category”]]
    

    Django docs indicate though that this may be deprecated and recommend the more fully featured UniqueConstraint meta option

    class Meta:
        constraints = [
            UniqueConstraint(fields=[“name”,”category”], name=“unique_object”)
        ]