如何设置一个拥有多个权限的用户的django用户权限?

时间:2018-07-01 18:19:23

标签: django django-models user-permissions django-users

我有以下想法。一个用户可以在多个公司中。用户在其所在的每个公司中都有不同的权限。 下面的示例不起作用,因为一个用户将始终具有相同的权限。

我应该如何设置我的用户模型,使每个公司的每个用户都有不同的权限?

那是我到目前为止尝试过的:

class User(AbstractUser):
    hourly_wage = models.DecimalField(decimal_places=2, max_digits=6, default=8.50)

    class Meta:
        permissions = (("is_general", "Can add people to his company and see everything"),
                       ("is_captain", "Can add/edit/delete everything"),
                       ("is_staff", "Can add/edit/delete jobs"),
                       ("is_programmer", "Can do what he or she wants to do"))

    def clean(self):
        self.username = self.username.lower()


class Company(models.Model):
    name = models.CharField(max_length=80)
    slug = models.SlugField(unique=True)
    users = models.ManyToManyField(User, related_name="companies")

    class Meta:
        verbose_name_plural = "companies"

1 个答案:

答案 0 :(得分:0)

您为ManyToManyField 定义一个模型,多对多关系通过该模型流动。

所以代替:

+---------+ M      N +-------------+ M      N +------------+
| Company |----------| User        |----------| Permission |
+---------+          +-------------+          +------------+
                     | permissions |
                     +-------------+

我们这样写:

+---------+ 1      N +-------------+ M      1 +------+
| Company |----------| UserCompany |----------| User |
+---------+          +-------------+          +------+
                            | M
                            |
                            | N
                     +------------+
                     | Permission |
                     +------------+

我们可以这样做:

from django.contrib.auth.models import Permission

class User(AbstractUser):

    def clean(self):
        self.username = self.username.lower()


class Company(models.Model):
    name = models.CharField(max_length=80)
    slug = models.SlugField(unique=True)
    users = models.ManyToManyField(User, through='app.CompanyUser', related_name="companies")

    class Meta:
        verbose_name_plural = "companies"


class CompanyUser(models.Model):

    user = models.ForeignKey('app.User', on_delete=models.CASCADE)
    company = models.ForeignKey('app.Company', on_delete=models.CASCADE)
    hourly_wage = models.DecimalField(decimal_places=2, max_digits=6, default=8.50)
    permissions = models.ManyToManyField(Permission, on_delete=models.CASCADE)

您可能想将其他逻辑转移到 through 模型。例如,hourly_wage也可能与(UserCompany)对相关,而不是特定于User本身。

您可以通过以下方式向UserCompany添加权限:

someusercompany.permissions.add(some_permission)

然后,您检查UserCompany是否具有以下权限:

CompanyUser.objects.filter(
    user=some_user,
    company=some_company,
    some_permission=some_permission
).exists()

documentation about through parameter [django-doc]中了解有关此内容的更多信息。