How to get a list of all users with a specific permission group in Django

前端 未结 9 786
遇见更好的自我
遇见更好的自我 2020-12-12 16:13

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(permi         


        
相关标签:
9条回答
  • 2020-12-12 16:38

    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>]
    
    0 讨论(0)
  • 2020-12-12 16:43

    Based on @Glader's answer, this function wraps it up in a single query, and has been modified to algo get the superusers (as by definition, they have all perms):

    from django.contrib.auth.models import User
    from django.db.models import Q
    
    def users_with_perm(perm_name):
        return User.objects.filter(
            Q(is_superuser=True) |
            Q(user_permissions__codename=perm_name) |
            Q(groups__permissions__codename=perm_name)).distinct()
    
    # Example:
    queryset = users_with_perm('blogger')
    
    0 讨论(0)
  • 2020-12-12 16:44

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

    from django.contrib.auth.models import User, Permission
    from django.db.models import Q
    
    perm = Permission.objects.get(codename='blogger')  
    users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct()
    
    0 讨论(0)
  • 2020-12-12 16:50

    This would be the easiest

    from django.contrib.auth import models
    
    group = models.Group.objects.get(name='blogger')
    users = group.user_set.all()
    
    0 讨论(0)
  • 2020-12-12 16:50

    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.

    0 讨论(0)
  • 2020-12-12 16:53

    Based on @Augusto's answer, I did the following with a model manager and using the authtools library. This is in querysets.py:

    from django.db.models import Q
    from authtools.models import UserManager as AuthUserManager
    
    class UserManager(AuthUserManager):
        def get_users_with_perm(self, perm_name):
            return self.filter(
                    Q(user_permissions__codename=perm_name) |
                    Q(groups__permissions__codename=perm_name)).distinct()
    

    And then in models.py:

    from django.db import models
    from authtools.models import AbstractEmailUser
    from .querysets import UserManager
    
    
    class User(AbstractEmailUser):
       objects = UserManager()
    
    0 讨论(0)
提交回复
热议问题