20

I have query:

items = MyModel.objects.all().order_by('nr')[:10]

and I get 10 items with higher number. Now I have to mix these results. How to do it?

Nips
  • 13,162
  • 23
  • 65
  • 103

3 Answers3

33

Curiously, this not very well documented feature works:

Country.objects.order_by('?')

source: http://www.jpstacey.info/blog/2008/09/03/random-ordering-of-query-results-in-django

Astonishingly, the existing documentation has very little Google juice, unless you search for "randomly" rather than "random".

AndyTheEntity
  • 3,396
  • 1
  • 22
  • 19
  • 6
    The reason why it's not very well documented is because doing it that way is going to cause huge performance issues on larger databases. http://stackoverflow.com/questions/1731346/how-to-get-two-random-records-with-django#6405601 – Llanilek May 24 '15 at 11:06
  • https://docs.djangoproject.com/en/3.0/ref/models/options/#ordering – suhailvs Jun 02 '20 at 08:25
21

You can't reorder a query once a slice has been taken, so use different approach

import random
items = sorted(MyModel.objects.all().order_by('nr')[:10], key=lambda x: random.random())
Sergey Lyapustin
  • 1,917
  • 17
  • 27
17

OK, you can't re-order a queryset after you've pulled it in, but you can do this instead

import random
items = list(MyModel.objects.all().order_by('nr')[:10])
random.shuffle(items)
moopet
  • 6,014
  • 1
  • 29
  • 36