源码分析
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()函数的注释和源码都可以看出:
- 使用order_by(None)会取消已存在的排序规则
- 使用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>]