简体   繁体   中英

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.

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.

order_by可以有多个参数,我认为order_by('score', '-create_time')将始终返回相同的查询集。

If I understand correctly, I think you need consistently ordered result set every time, You can use something like order_by('score','id') that will first order by the score first and then by the auto-increment id within the score having same values, hence your output being consistent. The documentation is here . You need to be explicit in the order_by if you want to fetch correct result set every time, using 'id' is one of the ways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM