好的方法来排序查询? - Django [英] Good ways to sort a queryset? - Django

查看:167
本文介绍了好的方法来排序查询? - Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是这样的:


  • 获得最高分的30位作者( Author.objects.order_by(' - score')[:30]

$ c> last_name

order the authors by last_name

任何建议?

推荐答案

如何

import operator

auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))

在Django 1.4和更新版本中,您可以通过提供多个字段进行排序。

参考: https://docs.djangoproject.com/en/ dev / ref / models / querysets /#order-by

In Django 1.4 and newer you can order by providing multiple fields.
Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

order_by(* fields)

默认情况下,由 QuerySet返回的结果按照由th给出的排序元组排序e 订购选项在模型的元。您可以使用 order_by 方法在每个QuerySet的基础上覆盖此。

By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.

示例: / strong>

Example:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

以上结果将按得分降序排序,然后由 last_name 升序。 前面的负号 - 得分表示降序。升序是隐含的。

The result above will be ordered by score descending, then by last_name ascending. The negative sign in front of "-score" indicates descending order. Ascending order is implied.

这篇关于好的方法来排序查询? - Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆