import random def fast_random_model(callback, queryset): """ Attempts to quickly retrieve a single randomly selected object from a queryset, then passes it to the callback if successful. """ # This implementation avoids using `order by random()` which is notoriously # slow with large tables in Postgres. count = queryset.count() try: random_index = random.randint(0, count - 1) except ValueError: pass # The queryset was empty. else: try: model = queryset[random_index] except IndexError: pass # Failed due to the race condition above. else: callback(model)