简体   繁体   English

Django - order_by如何工作?

[英]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. 我想知道如果给定的order_by字段的值对于一组记录是相同的,Django的order_by是如何工作的。 Consider I have a score field in DB and I'm filtering the queryset using order_by('score') . 考虑我在DB中有一个score字段,我使用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. 我正在使用Django 1.4和PostgreSQL。

As the other answers correctly explain, order_by() accepts multiple arguments. 正如其他答案正确解释的那样, order_by()接受多个参数。 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. 我建议在这些情况下使用'pk' (或'-pk' )作为最后一个参数,因为每个模型都有一个pk字段,并且它的值对于2个记录永远不会相同。

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. 如果我理解正确的话,我想你需要持续有序的结果集,每次,你可以使用类似order_by('score','id')是将第一级由得分第一,然后通过自动递增id的内score具有相同的值,因此您的输出是一致的。 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. 如果你想每次都获取正确的结果集,你需要在order_by中明确,使用'id'是其中一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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