Django QuerySet attributes之order_by()基础用法以及如何传递打包排序参数

本文详细介绍了Django QuerySet的order_by方法,包括默认排序、动态构造排序参数、跨模型排序以及如何避免清除先前的排序设置。还提供了如何向order_by传递打包排序参数的实例,确保在项目中的正确使用。
摘要由CSDN通过智能技术生成

本文分为两部分:

  • 官网相关部分文档
  • 展示如何向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(‘

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值