Shuffle queryset in Django

1.5k views Asked by At

I am looking to shuffle only part of queryset in django.

qs = [obj1(order=0), obj2(order=1), obj3(order=999), obj4(order=999), .....]

queryset is ordered by 'order' field which can be anything from 0 - 999.

the final result should be all objects that are not 999 will be ordered from 0 and up,

and only the objects with order of 999 will be shuffled.

Is it possible?

1

There are 1 answers

0
OrenD On BEST ANSWER

Given that the queryset is not too big to be sorted as a list, you can do the following:

shuffled = sorted(qs, key=lambda item: item.order if item.order != 999 else 999 + random.random())