-1

Here is the code from an other post :

from random import randint
count = article.objects.all().count()
random_index = randint(0, count - 1)
all_articles_query =  article.objects.all()
article = all_articles_query[random_index]

but now i would like to remove article from the list all_articles_query, and multiple time. I would like to sort a list of article then a random article and each time i sort a random article to move it from the list of article.

I would like to get all article one by one but in a random way.

Regards

Bussiere
  • 500
  • 13
  • 60
  • 119

2 Answers2

1

I think you can try like this using random.randrange:

import random

article_list = list(article.objects.all())  # evaluating queryset before everything

while article_list:
    sample = article_list.pop(random.randrange(len(article_list)))
    print(sample)
ruddra
  • 50,746
  • 7
  • 78
  • 101
0

You can use the Custom model manager to do that.

class ArticleManager(models.Manager):
    def random(self):
        count = self.aggregate(count=Count('id'))['count']
        random_index = randint(0, count - 1)
        return self.all()[random_index]

Then in Article model

class Article(models.Model):
    ...
    random_objects = ArticleManager()

Then in query use

Article.random_objects.random()
shafik
  • 6,098
  • 5
  • 32
  • 50