I have the following model I want to use to add rights to users that are part of a team:
class Rights(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
team = models.ForeignKey(Teams, on_delete=models.CASCADE)
read = models.BooleanField(default=True)
write = models.BooleanField(default=False)
edit = models.BooleanField(default=False)
Some Users need to be able to make new entries. Some are not allowed to have that possibility. So, if some user sends a request, how can I check if one or more of these boolean values are true or false for this specific user?
CodePudding user response:
You can obtain the Rights
object that point to myuser
and myteam
, and then inspect the read
, write
and/or edit
fields:
right = Rights.objects.get(user=myuser, team=myteam)
right.read # bool, True or False
right.write # bool, True or False
right.edit # bool, True or False
You can ensure that for each user
/team
combination, there is at most one record with:
from django.conf import settings
class Right(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
team = models.ForeignKey(Teams, on_delete=models.CASCADE)
read = models.BooleanField(default=True)
write = models.BooleanField(default=False)
edit = models.BooleanField(default=False)
class Meta:
constraints = [
models.UniqueConstraint(fields=('user', 'team'), name='unique_per_user_team')
]
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Note: normally a Django model is given a singular name, so
Right
instead of.Rights