user8758206
user8758206

Reputation: 2191

If a queryset value is in a list

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:

account_roles = <QuerySet [<Group: admin>, <Group: customer>]>
allowed_roles = ['admin', 'customer', 'supplier', 'observer']

if account_roles in allowed_roles:
   print('Authorised')

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:

if request.user.groups.exists():
   group = request.user.groups.all()[0].name

if group in allowed_roles:
   return view_fn(request, *args, **kwargs)

Can someone show me how this is done?

Upvotes: 1

Views: 483

Answers (2)

EthanHunt...
EthanHunt...

Reputation: 231

if queryset.filter(name__in=allowed_roles).exists():

For more info refer documentation: https://docs.djangoproject.com/en/3.2/ref/models/querysets/

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

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:

if request.user.groups.filter(name__in=allowed_roles).exists():
    # has such group …
else:
    # user is not a member of any allowed_roles …

Upvotes: 3

Related Questions