Query a Random Row With Django

Tuesday, May 14 2013 5:38 p.m.

Here's a gist for a drop-in Django manager class that allows you to return a random row.


It can be used in your models.py like this:

class QuoteManager(RandomManager):
    def random_filter(self):
        return self.filter(is_active=True)

class Quote(models.Model):
    quote = models.TextField()
    by = models.CharField(max_length=75)
    is_active = models.BooleanField(default=True)

    objects = QuoteManager()

    def __unicode__(self):
        return self.by

Advantages over using the order_by('?') is performance. Random sort at the database seems to be extremely slow on most databases even if the table only has a few thousand rows. Note that the count of records is cached for 5 minutes, so if the table changes often you may want to change that. A limitation is that it only returns one row.

django, programming, python

Subscribe RSS Feed Bookmark and Share

More Blog Entries
Ed Menendez' Facebook profile