Posted By

magicrebirth on 07/23/11


Tagged

random queryset


Versions (?)

Getting Random objects from a Queryset in Django


 / Published in: Django
 

URL: http://elpenia.wordpress.com/2010/05/11/getting-random-objects-from-a-queryset-in-django/

  1. # 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:
  2.  
  3. Book.objects.all().order_by('?')[:10]
  4.  
  5. # 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:
  6.  
  7. import random
  8. count = Book.objects.all().count()
  9. slice = random.random() * (count - 10)
  10. Book.objects.all()[slice: slice+10]

Report this snippet  

You need to login to post a comment.