How to Shuffle (Randomize) QuerySet in Django

Suppose you want get a random item from a QuerySet, It should be random but non repeating.
In many posts I saw they use my_list = MyModel.objects.order_by(“?”) but it will produce repeating items.

1st Step: get a QuerySet

my_qset = MyModel.objects.all()

2nd Step: convert it into a list

my_list = list(my_qset)

3rd Step: Shuffle the list

shuffle(my_list) # from random import shuffle

4th Step: Use a for in loop to iterate and check each item.

for item in my_list:
    print(item.id)

So simple! and that’s it.

Leave a Reply

Your email address will not be published.