Random Select in Django

June 12, 2010

I had a need to pick up a random band from the database, so that I could display a link to its website. I only wanted to do this where the score for the website was to the higher end of our review scale. This can be done in Django using order_by('?'):

lRandomWebsite = Band.objects.filter(website_review__gte=4).order_by('?')[0]


This is, in fact, really slow. It has to do a full table scan to get hold of all the rows before it finds one of them randomly. See the references link below for details and benchmarks.

A quicker way is to do this:

from random import randint

lWebsiteCount = Band.objects.filter(website_review__gte=4).count()
lRandomWebsite = Band.objects.filter(website_review__gte=4).all()[randint(0, lWebsiteCount-1)]


Tags: random django select