falsk模型-flask_sqlalchemy增删改查

1、增、删、改

增

python 复制代码
@home_bp.route('/useradd')
def user_add():
    users = []
    for i in range(10,20):
        user = User()
        user.name = '冰冰' + str(i)
        user.age = 20+i
        users.append(user)
    try:
        db.session.add_all(users)
        db.session.commit()
        return jsonify({'code':1,'info':'success'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code':0,'info':str(e)})

删

python 复制代码
#删
@home_bp.route('/userdel')
def user_del():
    user = User.query.first() # 查询第一条数据
    db.session.delete(user)
    try:
        db.session.commit()
        return jsonify({'code':1,'info':'success'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code':0,'info':str(e)})

改

python 复制代码
# 改:修改数据
#    找到要修改的数据,然后修改
@home_bp.route('/userupdate/')
def user_update():
    u = User.query.first()  # 查询第一条数据
    u.age = 1000
    db.session.commit()
    return jsonify({'code':1,'info':'success'})

2、查

(1)all(): 返回所有数据,返回列表

python 复制代码
    users = User.query.all()

    print(users, type(users))  # <class 'list'>

    print(users[0].name)  #冰冰01

    print(User.query, type(User.query))  # <class 'flask_sqlalchemy.query.Query'>

(2) filter() : 过滤,得到查询集,类似SQL中的where

python 复制代码
    users = User.query.filter(User.age==20)
    users = User.query.filter(User.age>20)  # 可以用于非等值操作
    print(list(users))  # [冰冰20]

(3) count(): 统计查询集(User.query.filter()中的数据条数

python 复制代码
     users = User.query.filter()
     print(users.count())  # 20

(4)filter_by() : 用于等值操作的过滤

python 复制代码
users = User.query.filter_by(age=20)

(5)get():查询到对应主键的数据对象

python 复制代码
    user = User.query.get(8)
    print(user, type(user))  # User对象 <class 'App.models.User'>
    print(user.name, user.age)  # 获取数据的属性

(6)limit() : 前几条:offset() : 跳过前几条

python 复制代码
   users = User.query.offset(3).limit(4)
   print(list(users))

(7)排序

复制代码
    users = User.query.order_by('age')  # 升序
    users = User.query.order_by(desc('age'))  # 降序

(8)and_,or_,not_

python 复制代码
     users = User.query.filter(User.age>20, User.age<25)  # 且,常用
     users = User.query.filter(and_(User.age>20, User.age<25))  # 且
     users = User.query.filter(or_(User.age>25, User.age<20))  # 或
     users = User.query.filter(not_(or_(User.age>25, User.age<20)))  # 非

(9) 模糊查找,类似SQL中的like

python 复制代码
users = User.query.filter(User.name.contains('3'))

(10) in_(): 其中之一

python 复制代码
users = User.query.filter(User.age.in_([10, 20, 30, 40, 50]))

(11) startswith() : 以某子串开头,endswith() : 以某子串结尾

python 复制代码
    users = User.query.filter(User.name.startswith('冰'))  #
    users = User.query.filter(User.name.endswith('2'))

(12)gt: 大于

python 复制代码
users = User.query.filter(User.age.__gt__(25))
相关推荐
高频因子挖掘机1 小时前
回测收益为什么可能不真实?从时间戳、数据可用性到未来函数检查
后端·github·api
宿州派大星2 小时前
Python实战:PyQt5 + OpenCV + Dlib 打造AI桌面应用
人工智能·python·qt
承渊政道3 小时前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(开源大模型ChatGLM高级定制化应用实战)
人工智能·pytorch·python·llm·模型微调·glm
行百里er9 小时前
Redis 完结篇——Redis 热点问题在 Spring Boot 项目中实战
redis·后端
Smoothcloud润云9 小时前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力
databook9 小时前
从循环到向量化:NumPy提速的7个关键思维
python·数据分析·numpy
棉猴10 小时前
玩游戏学Python1-Python和pgzero库的安装
python·pygame·玩游戏·pgzero·pgzrun
高频因子挖掘机10 小时前
只取最近 60 个交易日,却每次拉全历史:量化脚本变慢的原因与改法
后端·github·api
诺伦10 小时前
GEO优化数据实证:78%引用流向官网的机制拆解与小品牌三步管线实战教程 | RiseClaw玄策
python·seo·geo·内容营销·ai搜索
oooost10 小时前
pytorch学习笔记1
python·学习方法