-2

I'm using Django with Python 3.7 and PostGres 9.5. I use the following to get all my objects and iterate over them ...

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

Is there a way to modify my existing query or possibly the loop so that the objects are returned in a random order each time? I would prefer not to make a second query if at all possible.

Dave
  • 15,639
  • 133
  • 442
  • 830
  • 2
    Instead of asking on StackOverflow before doing any work, it's generally a good idea to google your question - `random.shuffle()` is hard to miss. – Grismar Jul 01 '19 at 01:34
  • maybe duplicate question?, check this link : [How to pull a random record using Django's ORM?](https://stackoverflow.com/questions/962619/how-to-pull-a-random-record-using-djangos-orm) – Ali Akhtari Jul 01 '19 at 02:05
  • Possible duplicate of [How to pull a random record using Django's ORM?](https://stackoverflow.com/questions/962619/how-to-pull-a-random-record-using-djangos-orm) – shafik Jul 01 '19 at 03:37

3 Answers3

3

As is explained in the documentation you can use order_by('?') as follows:

article_set = Article.objects.order_by('?')
ivissani
  • 2,614
  • 1
  • 18
  • 12
  • Note that `order_by('?')` queries may be expensive and slow. Try to avoid this if possible in your use case. – shafik Jul 01 '19 at 03:15
0

I'm not too familiar with Django, and correct me if I'm wrong but I'd assume that:

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

So I believe you should be able to do:

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

Which should mix up your output.


Otherwise, I'd say go with the random.shuffle approach.

from random import shuffle

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

Let me know if the order_by worked and I can edit accordingly. Like I said I'm not too familiar with Django so this is untested but in theory should work. Thanks!

Jab
  • 26,853
  • 21
  • 75
  • 114
0

Make a loop like this

article_set = Article.objects.all()
for article in random.shuffle(article_set):
    print(article)
Arun Augustine
  • 1,690
  • 1
  • 13
  • 20