akashrajkn
akashrajkn

Reputation: 2315

Check if user has one of the listed permissions in Django

I have the following issue. There is a list of permissions (suppose 'a' to 'z'). Each user has a subset of these permissions.

Suppose we have another list,

perms_list = [a, c, d]

I want to check if the user has at least one of the permissions in perms_list.

 user.has_perms(perms_list)

checks if the user has all the permissions, so, I cannot use this. (I also cannot use has_module_perms since, the permissions in my case have the same module)

The alternative is to put this in a for loop

for p in perms_list:
    if user.has_perm(p):
        # do_something

Is there a more efficient way of doing this?

As an extension to this question, is it possible have a generalised way of doing this? For example, user should have (perm1 and perm2) or perm3

Upvotes: 3

Views: 1369

Answers (1)

Smart Manoj
Smart Manoj

Reputation: 5824

if set(user.get_all_permissions()) & set(perms_list):
  pass

for the extension

a=[53,6]
b=[[53],[2,4,5]]
if any((set(x).issubset(a)) for x in b):
    print(23)

Upvotes: 3

Related Questions