0

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,

can it be done with pure sqlalchemy ? or should i create a for loop after a simpler query ?

  • I don't have any idea about Python sqlalchemy. But refer this [link](https://stackoverflow.com/questions/4186062/sqlalchemy-order-by-descending).You will get an idea – Thamarai T Apr 06 '19 at 04:11
  • Refer this first [link](https://stackoverflow.com/questions/16966163/sqlalchemy-order-by-calculated-column) – Thamarai T Apr 06 '19 at 04:19
  • Yes that comment gives me an idea that most people use desc() but i never tried on non numerical data like booleans, maybe i will try and validate what happens – Valen Learns Apr 06 '19 at 04:39

1 Answers1

0

Query results can be ordered by using the order_by method on your query. 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. The following should work for you.

session.query(MyModel).order_by(MyModel.is_urgent.desc(), MyModel.creation_time)
EAW
  • 628
  • 6
  • 10