Home > Back-end >  What's the most pythonic way to test if obj has any permission from a list
What's the most pythonic way to test if obj has any permission from a list

Time:09-09

In both Django and Django Guardian it's simple to test if a user has a permission:

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?

I know I can just chain an if/or statement, but this feels cumbersome:

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

CodePudding user response:

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)

CodePudding user response:

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.

There is another way to check if a user has permissions in a list by that 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

  • Related