Py学习  »  Django

在Django guardian中,我如何确定哪个组授予用户对对象实例的权限?

Ben • 3 年前 • 1419 次点击  

我正在尝试使用Django guardian和组设置对象级权限;我向组(而不是用户)授予权限,并根据需要从组中添加/删除用户。

当用户拥有与对象实例交互的权限时(因为他们所在的组具有必要的权限),我如何确定用户的哪些组授予了他们该权限?

例如,在 example in the django-guardian-docs ,理想情况下会有这样的情况:

>>> joe.has_perm_from_groups('sites.change_site', site)
[site_owners_group]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129337
 
1419 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Ben
Reply   •   1 楼
Ben    3 年前

Django guardian有一个快捷方式叫做 get_groups_with_perms(obj) 那个 Returns queryset of all Group objects with any object permissions for the given obj . https://django-guardian.readthedocs.io/en/stable/api/guardian.shortcuts.html#get-groups-with-perms

Django有一个名为 intersection 那个 returns the shared elements of two or more QuerySets https://docs.djangoproject.com/en/3.2/ref/models/querysets/#intersection

使用这两个函数,我可以找到用户所在的、对该对象也有权限的组。然后,我使用for循环来标识具有该权限的组。如果两个组都有权限,我不知道如何确定是哪一个组给了用户权限,因此返回找到的第一个组。

# Find the union of groups
groups = user.groups.all().intersection(get_groups_with_perms(obj))

# Check if any group has the permission, and return if True
for group in groups:
    if 'change_site' in get_perms(group, obj):
        return group
return None