Stuart Grimshaw
Stuart Grimshaw

Reputation: 1571

Order Django objects randomly

Here's an interesting problem, I have a list of users that I list in order of rating, and where two users have the same rating, I have a random number that I use to make sure the list won't always be the same.

Currently I do this by executing a query:

   select app_model1.column1, app_model1.colum2, app_model2.column3 
   from app_model1 left join app_model2 
   order by colum1, random();

But it struck me while refactoring a large Django app into several smaller ones that I'd hard coded the name of the table into this SQL, (and it broke my unit tests) and I should really be using the native ORM to achieve this.

How can I get the same result, but using Django's django.contrib.auth.User and a Profile model instead?

Upvotes: 0

Views: 348

Answers (1)

Ludwik Trammer
Ludwik Trammer

Reputation: 25042

According to the documentation you can use a special "?" field name:

    class Meta:
        ordering = ('colum1', '?')

Upvotes: 3

Related Questions