随机获取所有对象

时间:2019-01-28 08:09:09

标签: python django django-queryset

这是另一篇文章中的代码:

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]

但是现在我想从列表all_articles_query中删除文章,并多次删除。我想对文章列表进行排序,然后对随机文章进行排序,每次我对随机文章进行排序以将其从文章列表中移出时。

我想以随机方式逐篇获得所有文章。

致谢

2 个答案:

答案 0 :(得分:1)

我认为您可以使用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)

答案 1 :(得分:0)

您可以使用“自定义模型管理器”来执行此操作。

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]

然后在文章模型中

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

然后在查询中使用

Article.random_objects.random()