Sqlalchemy中取消已存在的排序规则

源码分析

order_by()函数的源码如下:

@inspection._self_inspects
@log.class_logger
class Query(object):
    @_generative(_no_statement_condition, _no_limit_offset)
    def order_by(self, *criterion):
        """apply one or more ORDER BY criterion to the query and return
        the newly resulting ``Query``

        All existing ORDER BY settings can be suppressed by
        passing ``None`` - this will suppress any ORDER BY configured
        on mappers as well.

        Alternatively, passing False will reset ORDER BY and additionally
        re-allow default mapper.order_by to take place.   Note mapper.order_by
        is deprecated.

        """

        if len(criterion) == 1:
            if criterion[0] is False:
                if '_order_by' in self.__dict__:
                    self._order_by = False
                return
            if criterion[0] is None:
                self._order_by = None
                return

        criterion = self._adapt_col_list(criterion)

        if self._order_by is False or self._order_by is None:
            self._order_by = criterion
        else:
            self._order_by = self._order_by + criterion

从order_by()函数的注释和源码都可以看出:

  1. 使用order_by(None)会取消已存在的排序规则
  2. 使用order_by(False)会重新使用默认的mapper.order_by定义的排序规则,但由于mapper.order_by已经弃用,所以一般来说和order_by(None)等效。

结果验证

>>> User.query.order_by(User.id.desc()).order_by(None).all()
[<User 1>, <User 2>, <User 3>, <User 4>, <User 5>]
>>> User.query.order_by(User.id.desc()).order_by(False).all()
[<User 1>, <User 2>, <User 3>, <User 4>, <User 5>]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值