sqlalchemy多列order_by

时间:2019-07-04 02:46:46

标签: python mysql sqlalchemy flask-sqlalchemy

我想要特定类型的未读消息并按创建时间排序,其他类型跟随未读消息,创建时间闪回(我要先输入type = 7和status = 0,然后要时间desc()然后再返回status = 1和时间desc( )) )

class Notifications(BaseModel):
    type = db.Column(db.Integer, default=0, index=True)
    status = db.Column(db.Boolean, default=False)
    create_time = db.Column(db.DateTime)



Notifications.query.filter(Notifications.type.in_([7,3,8])).
        order_by(case(((Notifications.type == 7, 1),
                           (Notifications.status == 0, 2),
                           (Notifications.status == 1, 3))),
                     Notifications.create_time.desc()).all()
{
"id": 938,
"status": 1,
"time": "2019-06-24 19:34:01",
"type": 7
},
{
"id": 889,
"status": 0,
"time": "2019-06-19 09:02:42",
"type": 7
},
{
"id": 918,
"status": 0,
"time": "2019-06-20 16:43:43",
"type": 8
},
{
"id": 936,
"status": 0,
"time": "2019-06-20 16:32:02",
"type": 3
}

0 个答案:

没有答案