33
loading...
This website collects cookies to deliver better user experience
order_by
causes Django to ask the database to order the rows by a given column.order_by
can trigger a series of very expensive and slow operations: getting a random row from the database.order_by('?')[0]
. Note though that the Django docs themselves give this warning:order_by('?')
queries may be expensive and slow
SELECT * FROM entry ORDER BY RAND() LIMIT 1
SELECT * FROM entry
entry
table.ORDER BY RAND()
LIMIT 1
order_by('?')[0]
is used then expect bad performance.order_by('?')[0]
being used:from random import randint
from django.db import models, transaction
class RandomManager(models.Manager):
@transaction.atomic
def random(self):
index = randint(0, self.count()-1)
return self.all()[index]
class Entry(models.Model):
objects = RandomManager()
random_item = Entry.objects.random()
transaction.actomic
to make both the count and the row read happen in the same transaction, preventing a rare race conditions occurring if:IndexError
could occur.