[英]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.