views:

1674

answers:

5

Hi,

I want to get a list of all Django auth user with a specific permission group, something like this:

user_dict = { 'queryset': User.objects.filter(permisson='blogger') }

But I cant seem to find out how to do this. How are the permissions groups saved in the user model?

+3  A: 

This would be the easiest

from django.contrib.auth import models

group = models.Group.objects.get(name='blogger')
users = group.user_set.all()
Daniel
+5  A: 

I think for group permissions, permissions are stored against groups, and then users have groups linked to them. So you can just resolve the user - groups relation.

e.g.

518$ python manage.py shell

(InteractiveConsole)
>>> from django.contrib.auth.models import User, Group
>>> User.objects.filter(groups__name='monkeys')
[<User: cms>, <User: dewey>]
cms
Thanks, that fixed it, i knew should be simple. The only problem is if the group name is changed, maybe i should filter it on ID or something instead...But thanks!
Espen Christensen
A: 

Groups are many-to-many with Users (you see, nothing unusual, just Django models...), so the answer by cms is right. Plus this works both ways: having a group, you can list all users in it by inspecting user_set attribute.

zgoda
A: 

Try this.

User.objects.filter(groups__permissions = Permission.objects.get(codename='blogger'))

+3  A: 

If you want to get list of users by permission, look at this variant:

perm = Permission.objects.get(codename='blogger')
users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm) ).distinct()

Glader