[Django]-Roles in django model

2👍

This might work. If the number of roles is large, or dynamic (as in roles can be added, removed, renamed, updated). You could introduce a ternary relation, like:

from django.conf import settings

class Role(models.Model):
    name = models.CharField(max_length=128)


class Team(models.Model):
    name = models.CharField('Name', max_length=128)
    members = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Membership')

    def __str__(self):
        return self.name

class Membership(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    team = models.ForeignKey(Team, on_delete=models.CASCADE)
    role = models.ForeignKey(Role, on_delete=models.PROTECT)

Leave a comment