sqlalchemy order_by用法总结

本文展示了如何在Python中使用SQLAlchemy进行模型查询,涉及倒序、多字段排序及自定义text函数应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from sqlalchemy import text
class Test(db.Model):
    __tablename__ = 'test'
    id = db.Column(db.Integer, primary_key=True)
    col_1 = db.Column(db.Integer)
    col_2 = db.Column(db.Integer)
    

with app.app_context():
    # 倒序
    test = Test.query.with_entities(Test.id, Test.col_1, Test.col_2).order_by(Test.id.desc()).all()
    # 多字段排序 
    test = Test.query.with_entities(Test.id, Test.col_1, Test.col_2).order_by(Test.id).order_by(Test.col_1).all()
 	# 或者
    test = Test.query.with_entities(Test.id, Test.col_1, Test.col_2).order_by(Test.id, Test.col_1).all()
    
# 使用text
with app.app_context():
    ## 按查询的第一个排序 
    test = Test.query.with_entities(Test.id, Test.col_1, Test.col_2).order_by(text('1')).all()
    ## 按查询的第一个倒序排序 
    test = Test.query.with_entities(Test.id, Test.col_1, Test.col_2).order_by(text('1 desc')).all()
    ## 多字段排序
    test = Test.query.with_entities(Test.col_1, Test.col_2).order_by(text('1 desc'), text('2')).all()
    ## 或者
    test = Test.query.with_entities(Test.col_1, Test.col_2).order_by(text('1 desc, 2 desc')).all()
    ## 按col_1排序
    test = Test.query.with_entities(Test.id, Test.col_1, Test.col_2).order_by(text('col_1')).all()
    ## 按col_1倒序排序
    test = Test.query.with_entities(Test.id, Test.col_1, Test.col_2).order_by(text('-col_1')).all()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值