【问题标题】:How do I order my objects in a random way?如何以随机方式订购我的物品?
【发布时间】:2019-11-11 17:27:26
【问题描述】:

我将 Django 与 Python 3.7 和 PostGres 9.5 一起使用。我使用以下内容获取所有对象并对其进行迭代...

article_set = Article.objects.all()
for article in article_set:

有没有办法修改我现有的查询或可能的循环,以便每次以随机顺序返回对象?如果可能的话,我宁愿不进行第二次查询。

【问题讨论】:

标签: python django python-3.x postgresql


【解决方案1】:

As is explained in the documentation you can use order_by('?')如下:

article_set = Article.objects.order_by('?')

【讨论】:

  • 请注意,order_by('?') 查询可能既昂贵又缓慢。如果可能,请在您的用例中尽量避免这种情况。
【解决方案2】:

这样循环

article_set = Article.objects.all()
for article in random.shuffle(article_set):
    print(article)

【讨论】:

    【解决方案3】:

    我对 Django 不太熟悉,如果我错了,请纠正我,但我会假设:

    Article.objects.all()
    #Roughly equates to:
    "SELECT * from articles"
    

    所以我相信你应该能够做到:

    Article.objects.all().order_by('RANDOM()')
    #Thus producing this SQL statement:
    "SELECT * from articles ORDER BY RANDOM()"
    

    这会混淆你的输出。


    否则,我会说使用random.shuffle 方法。

    from random import shuffle
    
    article_set = Article.objects.all()
    for article in shuffle(article_set):
        #do work
    

    让我知道 order_by 是否有效,我可以进行相应的编辑。就像我说的我对 Django 不太熟悉,所以这是未经测试的,但理论上应该可以。谢谢!

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多