how to make a unique object (not unique per field)
name : honda
category : car
name : honda
category : bike
name : honda
category : bike
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
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”)
]