I’m new to python but am surprised I can’t find another post with a similar question to mine. I’m trying to find a way to compare whether a queryset value is inside a list. Take this as an example:
JavaScript
x
6
1
account_roles = <QuerySet [<Group: admin>, <Group: customer>]>
2
allowed_roles = ['admin', 'customer', 'supplier', 'observer']
3
4
if account_roles in allowed_roles:
5
print('Authorised')
6
Essentially a user has account_roles
and I only want to print ‘authorised’ if a user with an admin
or customer
role is present. I can only get a comparison working for a single value, but an the entire list of values.
Example working for a single value only:
JavaScript
1
6
1
if request.user.groups.exists():
2
group = request.user.groups.all()[0].name
3
4
if group in allowed_roles:
5
return view_fn(request, *args, **kwargs)
6
Can someone show me how this is done?
Advertisement
Answer
You need to find out if there exists a Group
with a .name
of the group that is in the list. We can filter with an __in
lookup [Django-doc] and query with:
JavaScript
1
4
1
if request.user.groups.filter(name__in=allowed_roles).exists():
2
# has such group …
3
else:
4
# user is not a member of any allowed_roles …