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

前端 未结 9 788
遇见更好的自我
遇见更好的自我 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: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')
    

提交回复
热议问题