16

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
  • 12,112
  • 22
  • 60
  • 99

3 Answers3

25

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
  • 2,426
  • 21
  • 17
  • 5
    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,831
  • 17
  • 27
13

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
  • 5,804
  • 1
  • 29
  • 35