Random User Selection from Django QuerySet

  • Share this:

Code introduction


This function randomly selects a specified number of users from a Django queryset. It accepts a queryset and a maximum number of results, and returns a list of randomly selected user objects if the count of the queryset is less than the maximum number of results; otherwise, it returns a list of randomly selected users.


Technology Stack : Django, QuerySet, random.sample

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_select_users(queryset, max_results=10):
    """
    Randomly select a specified number of users from a Django queryset.
    
    Args:
        queryset (django.db.models.QuerySet): The queryset to select from.
        max_results (int): The maximum number of users to select. Defaults to 10.
    
    Returns:
        list: A list of randomly selected user objects.
    """
    import random
    if queryset.count() < max_results:
        return list(queryset)
    return random.sample(list(queryset), min(max_results, queryset.count()))