Here's my code:
from django.db import models
class Parent(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return str(self.name)
class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return str(self.name)
Parents in my database:
Rogan
Smith
Doe
In admin dashboard:
First, I create a child that has a name of John and his parent is Smith.. it works!
Now, after that, whenever I create a child that also has a name of John and this time with a parent of Doe or Rogan, it says:
"Child with this Name already exists."
I tried searching on Google but I can't seem to find the answer.
Not a native English speaker here, please bear with me.
CodePudding user response:
You work with a UniqueConstraint
[Django-doc]:
class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
def __str__(self):
return f'{self.name}'
class Meta:
constraints = [
models.UniqueConstraint(
fields=('name', 'parent_id'), name='unique_child_name_per_parent'
)
]