flask_sqlalchemy数据库遇到的问题

本文介绍如何使用Python的SQLAlchemy库进行升序降序查询及模糊查询(like操作)。通过具体的SQL语句与对应的Python代码对比,帮助读者快速掌握这两种常见查询方式的实现。

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

1.如何实现SQLAlchemy的升序降序查询?

源码:asc = public_factory(UnaryExpression._create_asc, ".expression.asc")
    desc = public_factory(UnaryExpression._create_desc, ".expression.desc")

例子:

SQL语句:select * from user order by age desc

Python代码:users = User.query.order_by(db.desc(User.age)).all()

2.如何实现SQLAlchemy的Select like的用法?

源码:def like(self, other, escape=None):
       """Implement the ``like`` operator.
         In a column context, produces the clause ``a LIKE other``.
         E.g.::
             select([sometable]).where(sometable.c.column.like("%foobar%"))
         :param other: expression to be compared
         :param escape: optional escape character, renders the ``ESCAPE``
           keyword, e.g.::
             somecolumn.like("foo/%bar", escape="/")
         .. seealso::
             :meth:`.ColumnOperators.ilike`
         """
         return self.operate(like_op, other, escape=escape)

例子:

SQL语句:select * from user where username like ‘%john%’

Python代码:users = User.query.filter(Product.username.like(‘%john%’)).all()

总结:其实这些如果能看得懂源代码的英语以及懂得SQL语句,基本可以通过查阅源码解决以上类似的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值