Granny Aching
Granny Aching

Reputation: 1435

How to test is user is one of the groups in a list of groups

I have a list of groups, and I want to test if the user belongs to any one of the groups.

I can get a list of user's groups:

user_groups = user_object.groups.all()

And I can use sets:

if not set(user_object.groups.all()).isdisjoint(group_list):

Is this the best way?


Added:

group_list comes from a many-to-many field from another model (MyClass.groups_allowed.all())

class MyClass(models.Model):
    ...
    groups_allowed = ManyToManyField(Group, default=None, blank=True)
    ...

    def user_can_view(self, user_object):
        ...
        if not set(user_object.groups.all()).isdisjoint(self.groups_allowed.all()):
            return True
        ...

Upvotes: 0

Views: 80

Answers (2)

alex2007v
alex2007v

Reputation: 1300

if group_list is queryset:

user_object.groups.filter(id__in=group_list.values_list('id', flat=True))

else you have get id from that list and do next:

user_object.groups.filter(id__in=groups_id_list)

it does just one request to your db

Upvotes: 0

Ashish
Ashish

Reputation: 459

You can check user's group like

if user_object.groups.filter(name = groupname).exists():
    pass

or

if user_object.groups.filter(name__in= groupname_list):
    pass

Upvotes: 1

Related Questions