How to code unique constraint per parent ForeignKey in Django model?

Question:

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:

  1. Rogan

  2. Smith

  3. 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."

here

I tried searching on Google but I can’t seem to find the answer.

Asked By: Norvz

||

Answers:

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