Reputation: 1435
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
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
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