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

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 

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)