Last active
August 29, 2015 14:02
-
-
Save rectangletangle/807febc7b54d551dcc85 to your computer and use it in GitHub Desktop.
Quickly select a random model from a Django queryset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment