Getting Random objects from a Queryset in Django

/ Published in: Django
Save to your folder(s)

Copy this code and paste it in your HTML
  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:
  3. Book.objects.all().order_by('?')[:10]
  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:
  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


RSS Icon Subscribe to comments

You need to login to post a comment.