Skip to content

Instantly share code, notes, and snippets.

@rectangletangle
Last active August 29, 2015 14:02
Show Gist options
  • Save rectangletangle/807febc7b54d551dcc85 to your computer and use it in GitHub Desktop.
Save rectangletangle/807febc7b54d551dcc85 to your computer and use it in GitHub Desktop.
Quickly select a random model from a Django queryset
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