postgresql Django - order_by 如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12775844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:23:56  来源:igfitidea点击:

Django - How does order_by work?

pythondjangopostgresqlsql-order-by

提问by Babu

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

order_by如果order_by一组记录的给定字段的值相同,我想知道 Django 的工作原理。考虑我score在数据库中有一个字段,我正在使用order_by('score'). 具有相同 score 值的记录将如何排列?

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。

回答by Anuj Gupta

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

正如其他答案正确解释的那样,order_by()接受多个参数。我建议使用类似的东西:

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 pkfield and its value is never the same for 2 records.

在这些情况下,我建议使用'pk'(or '-pk') 作为最后一个参数,因为每个模型都有一个pk字段,并且它的值对于 2 个记录来说永远不会相同。

回答by iMom0

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

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

回答by bhatiaravi

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 idwithin the scorehaving 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.

如果我理解正确的话,我觉得你一直需要有序的结果集,每次,你可以使用类似order_by('score','id')的分数通过自动递增第一,那么就会一阶id的内部score具有相同的值,因此您的输出是一致的。文档在这里。如果您想每次都获取正确的结果集,您需要在 order_by 中明确,使用 'id' 是其中一种方法。