/ Published in: Django
- # 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]
You need to login to post a comment.