Django ORM:使用链接表联接两个表

问题描述

我想在类has_permission(self,permission_name)中集成一个函数Profile。 为此,我想做一个ORM语句,该语句返回权限名称列表。

数据模型为:

  • 1 用户具有 1 个人资料(扩展了Django的用户模型)
  • 每个配置文件被分配给一个 ProfileGroup 。 但是,不同的个人资料可以属于同一个个人资料组
  • 每个 ProfileGroup 可以具有一个或多个 ProfilePermissions 。组可以具有相同的 ProfilePermissions 子集。链接表 GroupPermissions 使用两个ForeignKeys而不是ManyToMany关系来处理此问题。

我的models.py看起来像这样:

class ProfileGroup(models.Model):
    name = models.CharField(max_length=64)


class ProfilePermission(models.Model):
    name = models.CharField(max_length=64)


class GroupPermissions(models.Model):
    group = models.ForeignKey(ProfileGroup,on_delete=models.RESTRICT)
    permission = models.ForeignKey(ProfilePermission,on_delete=models.RESTRICT)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['group','permission'],name='Unique')
        ]

    def __str__(self):
        return f'Group "{self.group.name}" has permission "{self.permission.name}"'


class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    group = models.ForeignKey(ProfileGroup,on_delete=models.RESTRICT)

    def __str__(self):
        return f'Profile of {self.user.username}'

    def has_permission(self,permission_name):
        return True

函数has_permission(在Profile类中)应检查权限permission是否包含在“权限”列表中。我尝试过

list_of_permissions = GroupPermissions.objects.filter(group=self.group)

但这将返回ProfilePermission的列表。我需要的是权限名称列表(permission.name

因此,我必须将两个表GroupPermissionsProfilePermission合并在一起。我找到了prefetch_relatedselect_related这样的东西,但这并不能满足我的需求。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)