本文分为两部分:
- 官网相关部分文档
- 展示如何向order_by传递打包排序参数【项目中的实际使用情景】
官网相关部分文档
官网文档中的用法只涉及一般用法,适用于参数固定或者静态参情景,对于动态构造后面我会进行补充
order_by(*fields)¶
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.
默认情况下QuerySet的返回值是一个由定义模型时在Meta中给定的排序元组按序作用的结果,但是我们可以在每一个QuerySet的基上调用order_by方法重写这一行为。
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
# ...
class Meta:
ordering = ['-pub_date', 'author']
#注意这里,排序参数前如果有‘-’则代表着降序,没有则默认升序
#To order by pub_date descending, then by author ascending, use this:
you can also use query expressions. To order by author ascending and make null values sort last, use this:
from django.db.models import F
ordering = [F('author').asc(nulls_last=True)]
Regular example:
Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')#多静态参/固定参
The result above will be ordered by pub_date descending, then by headline ascending. The negative sign in front of “-pub_date” indicates descending order. Ascending order is implied. To order randomly, use “?”, like so:
Entry.objects.order_by('?')#此方法一般不用,消耗太高,影响性能
Note: order_by(‘