/ Published in: Django

Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
# 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: Book.objects.all().order_by('?')[:10] # 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]
URL: http://elpenia.wordpress.com/2010/05/11/getting-random-objects-from-a-queryset-in-django/
Comments
