0%

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

源码分析

order_by()函数的源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@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)等效。

结果验证

1
2
3
4
>>> 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>]