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