排序查询集的好方法?- 姜戈 [英] Good ways to sort a queryset? - Django
问题描述
我想做的是:
获取得分最高的 30 个作者 (
Author.objects.order_by('-score')[:30]
)
按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
返回的结果按模型元中的 ordering
选项给出的排序元组排序.您可以使用 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.
示例:
ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]
上面的结果将按score
降序排列,然后按last_name
升序排列."-score"
前面的负号表示降序.升序是隐含的.
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.
这篇关于排序查询集的好方法?- 姜戈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!