数据库基本操作
在Flask-SQLAlchemy中,插入、修改、删除操作,均由数据库会话管理。
会话用 db.session 表示。在准备把数据写入数据库前,要先将数据添加到会话中然后调用 commit() 方法提交会话。
在 Flask-SQLAlchemy 中,查询操作是通过 query 对象操作数据。
最基本的查询是返回表中所有数据,可以通过过滤器进行更精确的数据库查询。
首先定义模型类,主要是一对多,多对多的关系
常用的SQLAlchemy查询过滤器
过滤器 说明
filter() 把过滤器添加到原查询上,返回一个新查询
filter_by() 把等值过滤器添加到原查询上,返回一个新查询
limit 使用指定的值限定原查询返回的结果
offset() 偏移原查询返回的结果,返回一个新查询
order_by() 根据指定条件对原查询结果进行排序,返回一个新查询
group_by() 根据指定条件对原查询结果进行分组,返回一个新查询
常用的SQLAlchemy查询执行器
方法 说明
all() 以列表形式返回查询的所有结果
first() 返回查询的第一个结果,如果未查到,返回None
first_or_404() 返回查询的第一个结果,如果未查到,返回404
get() 返回指定主键对应的行,如不存在,返回None
get_or_404() 返回指定主键对应的行,如不存在,返回404
count() 返回查询结果的数量
paginate() 返回一个Paginate对象,它包含指定范围内的结果
创建表:
db.create_all()
删除表
db.drop_all()
查询:filter_by精确查询
返回名字等于wang的所有人
User.query.filter_by(name=‘wang’).all()
first()返回查询到的第一个对象
User.query.first()
all()返回查询到的所有对象
User.query.all()
filter模糊查询,返回名字结尾字符为g的所有数据。
User.query.filter(User.name.endswith(‘g’)).all()
get():参数为主键,如果主键不存在没有返回内容
User.query.get()
逻辑非,返回名字不等于wang的所有数据
User.query.filter(User.name!=‘wang’).all()
not_ 相当于取反
from sqlalchemy import not_
User.query.filter(not_(User.name==‘chen’)).all()
逻辑与,需要导入and,返回and()条件满足的所有数据
from sqlalchemy import and_
User.query.filter(and_(User.name!=‘wang’,User.email.endswith(‘163.com’))).all()
逻辑或,需要导入or_
from sqlalchemy import or_
User.query.filter(or_(User.name!=‘wang’,User.email.endswith(‘163.com’))).all()
查询数据后删除
user = User.query.first()
db.session.delete(user)
db.session.commit()
User.query.all()
更新数据
user = User.query.first()
user.name = ‘dong’
db.session.commit()
User.query.first()