Norvz
Norvz

Reputation: 27

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

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.

Upvotes: 1

Views: 215

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476537

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'
            )
        ]

Upvotes: 1

Related Questions