Random User Selection from Django Group

  • Share this:

Code introduction


This function randomly selects a user from a specified Django group. If there are no users in the group, it returns None.


Technology Stack : Django, Group, User, random

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_select_user_from_group(group_id, user_model):
    from django.contrib.auth.models import Group
    from random import choice
    
    group = Group.objects.get(id=group_id)
    users = list(group.user_set.all())
    return choice(users) if users else None