[英]How do i order_by a query so that all rows with a column equal to true go at first?
So i have a model : 所以我有一个模型:
id = db.Column(db.Integer, primary_key=True)
is_urgent = db.Column(db.Boolean, default=False)
creation_time = db.Column(db.DateTime, index=True, default=datetime.utcnow)
and i want to create a ordered list by a query so that all orders that are urgent go first and then all that arent urgent. 并且我想通过查询创建一个有序列表,以便所有紧急的订单首先出现,然后是所有不紧急的。 And those two gropus are also ordered by creation time, so the first order of the query list would be the oldest urgent order and the most recent would be the not-urgent newest one, 并且这两个gropus也按创建时间排序,因此查询列表的第一个顺序是最旧的紧急订单,最新的紧急订单是最近的紧急订单,
can it be done with pure sqlalchemy ? 可以用纯粹的sqlalchemy来完成吗? or should i create a for loop after a simpler query ? 或者我应该在更简单的查询后创建一个for循环?
Query results can be ordered by using the order_by
method on your query. 可以使用查询中的order_by
方法对查询结果进行排序。 This takes multiple arguments and your query will be sorted by each of these in turn. 这需要多个参数,您的查询将依次按每个参数进行排序。 The desc
method on each of the columns supplied to order_by
can be used to control the direction of the sort. 提供给order_by
每个列的desc
方法可用于控制排序的方向。 The following should work for you. 以下内容适合您。
session.query(MyModel).order_by(MyModel.is_urgent.desc(), MyModel.creation_time)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.