How to set a UniqueConstraint in a ManyToMany relationship in Django Models

  django, django-models, python

I have a model (MyModel) which can have multiple User as owners (ManyToMany relationship). Each User can own multiple MyModel instances.

The idea is that a user can create a MyModel instance through an API. But I want to set a constraint that the MyModel instance that the users create has to have a unique name within the MyModels that the user owns. It can be non-unique across the database though.

I am trying to do so by explicitly defining a MyModelOwner as the through model in a ManyToMany field but I am confused on how should I handle the UniqueConstraint?

class MyModel(models.Model):
    id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
    name = models.CharField(
        max_length=1000,
        unique=True,
    )
    owner = models.ManyToManyField(
        User,
        related_name='+',
        through='MyModelOwner'
    )


class MyModelOwner(models.Model):
    my_model = models.ForeignKey(MyModel, on_delete=models.PROTECT)
    owner = models.ForeignKey(User, on_delete=models.PROTECT)

    class Meta:
        constraints = [
            UniqueConstraint(
                fields=['owner', 'my_model'],
                name='unique_my_model_owner'),
        ]

Source: Python Questions

LEAVE A COMMENT