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.
order_by
can have multiple params, I think order_by('score', '-create_time')
will always return the same queryset.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With