Mr B
Mr B

Reputation: 4130

How to retrieve all usernames alongside a boolean flag for each user to indicate their membership to a group?

I am trying to build a page which allows the admin user to toggle membership to a particular group for each user. I aim to do this with AJAX functionality. I am using Django 2.2.

I have implemented an AJAX call which returns all users in the system - this data populates a data table. The next step is to have a checkbox next to each user, indicating their membership to a group.

I am using the code below in my view to retrieve users.

users = list(GeminiUser.objects.filter(is_active=1).values('email'))

I want the users query result to contain a boolean field for each user indicating their membership to a particular group. How can I achieve this?

Appreciate any guidance.

Upvotes: 2

Views: 153

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477170

We can do this with a subquery and with an Exists [Django-doc]:

from django.db.models import Exists, OuterRef

in_group = Group.objects.filter(
    pk=mygroup.pk,
    user=OuterRef('pk')
)

my_users = User.objects.annotate(in_group=Exists(in_group))

with mygroup.pk the primary key of the group for which you want to check membership.

This queryset contains User objects with an extra attribute in_group that is True if the user belongs to the group, and False otherwise.

For example:

>>> from django.contrib.auth.models import Group, User
>>> mygroup = Group.objects.first()
>>> from django.db.models import Exists, OuterRef
>>> 
>>> in_group = Group.objects.filter(
...      pk=mygroup.pk,
...      user=OuterRef('pk')
... )
>>> 
>>> my_users = User.objects.annotate(in_group=Exists(in_group))
>>> my_users
<QuerySet [<User: >, <User: test>]>
>>> [u.in_group for u in my_users]
[True, False]

You can perform extra filtering on the queryset as well, such that it for example only shows active users, etc.

As for the serialization, please use a serializer [Django REST framework doc] [Django-doc]. Using .values() is not recommended at all. By separating the query and representation, you make it easier to extend, update, etc. your REST views.

Upvotes: 4

Related Questions