zaadeh
zaadeh

Reputation: 1861

On a django model, how to check uniqueness in the set of values in a ManyToMany field?

For example if I have a set of models like this, how can I make sure that only one Group instance with the same exact set of Permissions could exist in the model?

class Permission(models.Model):
    name = models.CharField(max_length=100, unique=True)

class Group(models.Model):
    name = models.CharField(max_length=100, unique=True)
    permissions = models.ManyToManyField(Permission)

class User(models.Model):
    name = models.CharField(max_length=100, unique=True)
    group = models.ForeignKey(Group)

What is the best way to enforce this constraint in django? I don't care about a DB-level constraint. Does django provide an existing flag on the ManyToMany model field or I need to add custom data validation? And if yes, how?

Also I don't use ModelForms, so form validation is not what I want.

My question is about uniqueness of set of ManyToMany field relations across the whole model, not in a single instance.

Upvotes: 1

Views: 846

Answers (1)

Leistungsabfall
Leistungsabfall

Reputation: 6488

You can override the Group model's save method in order to check uniqueness before saving Group objects.

For example:

class Group(models.Model):
    ...
    def save(self, *args, **kwargs):
        if insert_your_check_here():
            super(Group, self).save(*args, **kwargs) # Call the "real" save() method.
        else:
            return

For more information about overriding predefined model methods take a look at the docs.

Upvotes: 1

Related Questions