Ed Menendez
© 2024 All rights reserved.
Query a Random Row With Django
Here's a gist for a drop-in Django manager class that allows you to return a random row.
Model.objects.random()
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 __str__(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.