views:

49

answers:

1

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?

+3  A: 

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

    class Meta:
        ordering = ('colum1', '?')
Ludwik Trammer
I could, but the query picks out a list of Users, but orders them by a value in the Profile model, the ordering in that example only applies to the object that you apply the Meta class to. I'll have to try it and see I guess ... watch this space.
Stuart Grimshaw
You can use '?' anywhere you order in Django.`Entry.objects.order_by('?')`
Ludwik Trammer