3

Consider the following query:

candidates = Candidate.objects.filter(ElectionID=ElectionIDx)

Objects in this query are ordered by their id field.

How do I randomise the order of the objects in the query? Can it be done using .order_by()?

cbuch1800
  • 923
  • 3
  • 11
  • 26
  • 1
    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) – Mohammad Ashraful Islam Feb 17 '18 at 19:11
  • @AshrafulIslam Thank you, that link is very useful. Question is slightly different but the information is 100% relevant and helpful. – cbuch1800 Feb 17 '18 at 19:16

1 Answers1

2

Yes, you can use the special argument ? with order_by to get randomized queryset:

Candidate.objects.filter(ElectionID=ElectionIDx).order_by('?')

Doc

Note that, depending on the DB backend, the randomization might be slow and expensive. I would suggest you to do the benchmark first. If you feel it's slow, then try finding alternatives, before that go with ? first.

heemayl
  • 39,294
  • 7
  • 70
  • 76
  • Note that according to the documentation these "queries may be expensive and slow, depending on the database backend you’re using." – kszl Feb 17 '18 at 19:05
  • @BUZZY is there a less expensive way of achieving the same outcome? – cbuch1800 Feb 17 '18 at 19:09
  • @cbuch1800 Do the benchmark first. If you feel it's slow, then try finding alternatives, before that go with `?` first. – heemayl Feb 17 '18 at 19:10