Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering Base Django User by multiple groups

In my Django project I’m using base Django User and Group models. My goal is to get User queryset containing all User object who are assigned to multiple groups at the same time.
For example I two groups and three users:

from django.contrib.auth.models import User, Group

a = Group.objects.create(name='a')
b = Group.objects.create(name='b')

user_a = User.objects.create_user('a', 'a@a.com', 'a')
user_a.groups.add(a)
user_b = User.objects.create_user('b', 'b@b.com', 'b')
user_b.groups.add(b)
user_ab = User.objects.create_user('ab', 'ab@ab.com', 'ab')
user_ab.groups.add(a)
user_ab.groups.add(b)

I have tried filtering using __in on groups nad Q, but with no effect

from django.db.models import Q

User.objects.filter(groups__in=[a,b]).distinct()
<QuerySet [<User: a>, <User: ab>, <User: b>]>
User.objects.filter(Q(groups=a) & Q(groups=b))
<QuerySet []>

My expected result would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

User.objects.filter(???)
<QuerySet [<User: ab>]>

>Solution :

You can implement two JOINs by using two .filter(…) clauses [Django-doc], and thus filter with:

User.objects.filter(groups=a).filter(groups=b)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading