如何获得用户权限?(How to get user permissions?)

2019-09-03 11:51发布

我想检索用户作为premission ID的但列表中的所有权限:

user.get_all_permissions()

给我的权限名称列表。 怎么做?

Answer 1:

最关键的是得到这样的许可对象:

from django.contrib.auth.models import Permission
permissions = Permission.objects.filter(user=user)

在那里你可以访问id属性是这样的:

permissions[0].id

如果您想要列表(id, permission_name)执行以下操作:

perm_tuple = [(x.id, x.name) for x in Permission.objects.filter(user=user)]

希望能帮助到你!



Answer 2:

获取给定用户的所有权限,还与一组相关的权限此用户的一部分:

from django.contrib.auth.models import Permission

def get_user_permissions(user):
    if user.is_superuser:
        return Permission.objects.all()
    return user.user_permissions.all() | Permission.objects.filter(group__user=user)


Answer 3:

我们可以得到用户许可的用户对象直接到像这样的列表

perm_list = user_obj.user_permissions.all().values_list('codename', flat=True)

试试这个....



Answer 4:

这是为了查询返回的Permission对象的例程user.get_all_permissions()在单个查询。

from functools import reduce
from operator import or_
from django.db.models import Q
from django.contrib.auth.models import Permission

def get_user_permission_objects(user):
    user_permission_strings = user.get_all_permissions()
    if len(user_permission_strings) > 0:
        perm_comps = [perm_string.split('.', 1) for perm_string in user_permission_strings]
        q_query = reduce(
            or_,
            [Q(content_type__app_label=app_label) & Q(codename=codename) for app_label, codename in perm_comps]
        )
        return Permission.objects.filter(q_query)
    else:
        return Permission.objects.none()

或者,直接查询权限:

from django.db.models import Q
from django.contrib.auth.models import Permission

def get_user_permission_objects(user):
    if user.is_superuser:
        return Permission.objects.all()
    else:
        return Permission.objects.filter(Q(user=user) | Q(group__user=user)).distinct()




Answer 5:

from django.contrib.auth.models import Permission
permissions = Permission.objects.filter(user=user)

permissions[0].id


文章来源: How to get user permissions?