MiniGunnR
MiniGunnR

Reputation: 5800

How to get all users of a group in Django?

I want to get a list of all users who are within a Django Group. For example:

User.objects.filter(group='Staff')

I cannot find how to do this query anywhere in the docs.

Upvotes: 47

Views: 36840

Answers (2)

Malachi Bazar
Malachi Bazar

Reputation: 1823

This query allows you to find users by group id rather than by group name:

group = Group.objects.get(id=group_id)
users = group.user_set.all()

Here's a query that lets you search by group name:

users = User.objects.filter(groups_name='group_name')

Upvotes: 14

MiniGunnR
MiniGunnR

Reputation: 5800

The following query solved my problem.

User.objects.filter(groups__name='Staff')

Thanks to @SardorbekImomaliev for figuring it out.

Upvotes: 94

Related Questions