Sort django users with specific groups on the top

Viewed 190

All users of the application are mapped to at least one group. Here is list of available groups:

>>>Group.objects.all()
<QuerySet [<Group: superuser>, <Group: maintainer>, <Group: admin>, <Group: executive>, <Group: client>, <Group: other>]> 

When I render all the users in the queryset with .all(), I want to sort them with a specific custom order such that, all the Superusers should be on the top, then Admins, then Executives and then rest of the Users as per below list.

custom_sort_order = ['superuser', 'admin', 'executive', 'client', 'maintainer', 'other']

Wondering, how can I use sorted() function on my queryset:

class UserList(generic.ListView):
    model = User
    queryset = User.objects.all()
    template_name = 'users/users.html' 
    paginate_by = 10
1 Answers

You can sort user group name by looking in to the custom_sort_order:

def get_queryset(self):
    qs = super().get_queryset() 
    custom_sort_order = ['superuser', 'admin', 'executive', 'client', 'maintainer', 'other']
    return sorted(qs, key=lambda item: custom_sort_order.index(item.groups.first().name)) 
Related