Issue
Here is my code:
Importing models from django.db
Class parent (models.Model):
Name = models.CharField(max_length=50, unique=True)
def __str__(self):
return str(self.name)
Children of the class (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)
Parent in database:
Logan
Smith
Dough
Management Dashboard:
First I created a child named John and his parent is he Smith.. worked!
After that, every time you create a child named John, this time with a parent of Doe or Rogan, you will see:
“A child with this name already exists.”
I’ve searched on Google but can’t seem to find an answer.
Solution
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'
)
]
Answered By – Willem Van Onsem
Answer Checked By – Pedro (Easybugfix Volunteer)