Flask的模型和数据库的增删改查

本文介绍了Flask框架中如何定义模型,并详细讲解了数据库的增、删、改、查操作,包括排序、分页、比较查询、模糊查询和多条件查询等实用技巧。

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

一.Flask的模型

安装Flask-SQLAlchemy
    
pip install sqlalchemy

(1)在models.py中定义:

 db = SQLAlchemy()

(2)在manage.py中:

 app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1:3306/flask8'
 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
 db.init_app(app)    

二.Flask数据库的增删改查:

1.增

增加学生信息
db.session.add(stu)
sb.session.commit()
批量增加学生信息
db.session.add_all(stus)
db.session.commit()

2.删

db.session.delete(stu)
db.session.commit()

3.改

db.session.add(stu) : 更新内容可以不写
db.session.commit()

4.查

三种查询主键的方式:
Student.query.filter(Student.id == 1).first()
stu = Student.query.filter_by(id=1).first()
stu = Student.query.get(1)

查询第一个对象:
stu1 = Student.query.all()[0]
stu2 = Student.query.first()

(1)排序

order_by('-id') :表示安装id的降序排数据
order_by('id') :表示安装id的升序排数据

(2)分页

方法1(切片):
stus = Student.query.all()[:4]
方法2:
offset(m).limit(n):表示跳过m个参数,截取n个参数

(3)比较符号

gt ge lt le : 大于 大于等于 小于 小于等于
stus = Student.query.filter(Student.s_age.__gt__(30)).all()

第二种(直接使用> < >= <= ):
stus = Student.query.filter(Student.s_age > 30).all()

(4)模糊查询

包含查询:
stus = Student.query.filter(Student.s_name.contains('d')).all()

以什么开头:
stus = Student.query.filter(Student.s_name.startswith('p')).all()

以什么结尾:
stus = Student.query.filter(Student.s_name.endswith('e')).all()

模糊查询('_' 匹配一位,'%' 匹配任意长度的数据):
stus = Student.query.filter(Student.s_name.like('__a%')).all()

(5)多条件查询

且:
    1.链式结构查询:
    stus = Student.query.filter(Student.s_name.contains('e')).filter(Student.s_age > 35).all()

    2._and方法或者,号隔开
    stus = Student.query.filter(and_(Student.s_name.contains('e'), Student.s_age > 35)).all()
    stus = Student.query.filter(Student.s_name.contains('e'), Student.s_age > 35).all()
或:
    or_方法:
    stus = Student.query.filter(or_(Student.s_name.contains('e'), Student.s_age > 35)).all()

非:
    not_方法:
    stus = Student.query.filter( not_(Student.s_name.contains('e') )).all()

(6)分页

第一种方法(切片):
            
第二种方法(limit offset):
    
第三种方法(paginate):
    has_prev/has_next 是否有上一页/下一页
    
    prev_num/next_num 上一页/下一页 的页码
    
    page:当前页码 pages:总页数
    
    循环取页码 iter_pages()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值