简体   繁体   English

测试 obj 是否具有列表中的任何权限的最pythonic方法是什么

[英]What's the most pythonic way to test if obj has any permission from a list

In both Django and Django Guardian it's simple to test if a user has a permission:在 Django 和 Django Guardian 中,测试用户是否具有权限很简单:

user.has_perm('app.can_eat_pizzas')

It's also easy to test if it has all permissions:测试它是否拥有所有权限也很容易:

user.has_perms(('app.add_student', 'app.can_deliver_pizzas'))

What's the most pythonic way to test if the user has any permission?测试用户是否有任何权限的最pythonic方法是什么?

I know I can just chain an if/or statement, but this feels cumbersome:我知道我可以链接一个 if/or 语句,但这感觉很麻烦:

if user.has_perm('app.add_student') or user.has_perm('app.can_deliver_pizzas')

I would do something like:我会做类似的事情:

if any(user.has_perm(perm_name) for perm_name in permission_list):
    # rest of code

(Using generator inside any() has an additinal benefit that it stop checking elements of the list after first True evaluation) (在any()中使用generator还有一个额外的好处,即它在第一次True评估后停止检查列表的元素)

You can get user all permissions by using user.user_permissions.all() or along with user.user_permissions.all().count() by checking length of permission objects if length is greater than 0.如果长度大于 0,您可以使用user.user_permissions.all()或通过检查权限对象的长度与user.user_permissions.all().count()一起获取用户所有权限。

There is another way to check if a user has permissions in a list by that user.user_permissions.filter(pk__in=<list>)还有另一种方法可以通过user.user_permissions.filter(pk__in=<list>)检查用户是否在列表中具有权限

perms = Permission.objects.filter(pk__in=list)
perms.user.all()

Either you can get users based on permission or filter the by permissions list.您可以根据权限获取用户,也可以按权限列表过滤。

Hope it may help you希望它可以帮助你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在此函数中传递kwargs的最pythonic方法是什么? - What is the most pythonic way to pass kwargs in this function? 引发与IntegrityError相关的异常时,获取字段名称的最pythonic方法是什么? - What's the most pythonic way to get name of the field when an exception related to IntegrityError is thrown? 初始化 Django object 的最优雅或 Pythonic 方式是什么? - What is the most elegant or Pythonic way to initialise a Django object? 在MyModelAdmin的has_delete_permission(self,request,obj = obj)中obj始终为None - obj is always None in MyModelAdmin's has_delete_permission(self, request, obj=obj) 更多pythonic测试方法 - more pythonic way to test 什么是编写此函数声明的更Python方式 - What's a more pythonic way to write this function declaration 在QuerySet中找到最流行选择的最Django / Python方法 - most django/pythonic way to find the most popular choice in queryset has_object_permission 和 has_permission 之间有什么区别? - What's the differences between has_object_permission and has_permission? 在运行时动态加载客户端库的大多数Pythonic / Django方法 - Most Pythonic/Django way to dynamically load client libraries at runtime 为链接建立完整网址的pythonic方法是什么? - What is the pythonic way of building full urls for links?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM