Random ordering of query results in Django September 3rd, 2008

In Django, when you have a queryset—a set of objects returned by an object manager, as yet not evaluated to actual objects—and you want them ordered randomly, set your order_by parameter to be a string of a single question mark:

>>> from mysite.models import Country
>>> Country.objects.order_by(’?')
>>> Country.objects.filter(continent=’Europe’).order_by(’?')

The objects should then be iterable in a random order.

Astonishingly, the existing documentation has very little Google juice, unless you search for “randomly” rather than “random”. Otherwise, at most you get db-api.txt telling you about using ordering tuples when you build your model.

Comments are closed.