Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How does order_by work?

I'd like to know how Django's order_by works if the given order_by field's values are same for a set of records. Consider I have a score field in DB and I'm filtering the queryset using order_by('score'). How will records having the same values for score arrange themselves?

Every time, they're ordered randomly within the subset of records having equal score and this breaks the pagination at client side. Is there a way to override this and return the records in a consistent order?

I'm Using Django 1.4 and PostgreSQL.

like image 246
Babu Avatar asked Oct 08 '12 05:10

Babu


2 Answers

order_by can have multiple params, I think order_by('score', '-create_time') will always return the same queryset.

like image 42
iMom0 Avatar answered Oct 05 '22 10:10

iMom0


As the other answers correctly explain, order_by() accepts multiple arguments. I'd suggest using something like:

qs.order_by('score','pk') #where qs is your queryset

I recommend using 'pk' (or '-pk') as the last argument in these cases, since every model has a pk field and its value is never the same for 2 records.

like image 116
Anuj Gupta Avatar answered Oct 05 '22 12:10

Anuj Gupta