Django: How to filter Users that belong to a specific group

This is a really old question, but for those googling the answer to this (like I did), please know that the accepted answer is no longer 100% correct. A user can belong to multiple groups, so to correctly check if a user is in some group, you should do:

qs = User.objects.filter(groups__name__in=['foo'])

Of course, if you want to check for multiple groups, you can add those to the list:

qs = User.objects.filter(groups__name__in=['foo', 'bar'])

You'll want to use Django's convention for joining across relationships to join to the group table in your query set.

Firstly, I recommend giving your relationship a related_name. This makes the code more readable than what Django generates by default.

class Group(models.Model):
    myuser = models.ForeignKey(User, related_name='groups')

If you want only a single group, you can join across that relationship and compare the name field using either of these methods:

form.fields['myuser'].queryset = User.objects.filter(
    groups__name='foo')
form.fields['myuser'].queryset = User.objects.filter(
    groups__name__in=['foo'])

If you want to qualify multiple groups, use the in clause:

form.fields['myuser'].queryset = User.objects.filter(
    groups__name__in=['foo', 'bar'])

If you want to quickly see the generated SQL, you can do this:

qs = User.objects.filter(groups__name='foo')
print qs.query 

Tags:

Python

Django