Return to Snippet

Revision: 49508
at July 23, 2011 01:15 by magicrebirth

Initial Code
# When providing related or suggested info to the user in a website, it’s a common practice to obtain a random set of items. To do this in django the “usual” way is:


# The above code, sorts all books in a random order and then picks the first 10 objects. This approach is not really efficient en MySQL. Since the “ORDER BY ?” clause is really expensive. So, a good way to obtain random elemets (actually a random slice) is the following:

import random
count = Book.objects.all().count()
slice = random.random() * (count - 10)
Book.objects.all()[slice: slice+10]

Initial URL

Initial Description

Initial Title
Getting Random objects from a Queryset in Django

Initial Tags

Initial Language