项目印记
预测未来的最好办法,就是把它创造出来。--艾伦.凯(美)
Flask-SQLAlchemy常用方法
常用查询方法
all()返回所有记录
Note.query.all()
first()返回第一条记录,没有返回None
first_or_404()返回第一个条记录,没有返回404错误响应
Note.query.first()
Note.query.first_or_404()
get()返回指定主键值(id字段)的记录
get_or_404返回指定主键值(id字段)的记录,没有返回404错误响应
Note.query.get(1)
Note.query.get_or_404(1)
count()返回记录的数量
Note.query.count()
paginate()返回一个Pagination对象,可以对记录进行分页处理
Comment.query.order_by(Comment.timestamp.desc()).paginate(page, per_page)
# page:当前页
# per_page:每页记录数
with_parent(instance)传入模型类实例作为参数,返回和这个实例相关联的对象
post = Post.query.get(2)
comment = Comment.query.with_parent(post).filter(Comment.post_id==post.id).first_or_404()
常用过滤方法
filter()使用指定的规则过滤记录,返回新产生的查询对象
Note.query.filter(Note.title =='flask').first()
# 除了‘==’和'!='外,其他常用操作符 LIKE、IN、NOTIN、AND、OR等
LIKE:
filter(Note.content like('%foo%'))
IN:
filter(Note.content in_(['foo','bar','baz']))
NOTIN:
filter(~Note.content in_(['foo','bar','baz']))
AND:
from sqlalchemy import and_
filter(and_(Comment.author_id == 1, Comment.is_accept == True))
或者:多个表达式中间用逗号隔开
filter(Comment.author_id == 1, Comment.is_accept == True)
或者:调用多个filter
filter(Comment.author_id == 1).filter(Comment.is_accept == True)
OR:
from sqlalchemy import or_
filter(or_(Comment.author_id == 1, Comment.is_accept == True))
filter_by()使用指定规则过滤记录(以关键字表达式的形式),返回新产生的查询对象
Note.query.filter_by(title='flask').first()
order_by()根据指定规则排序
Note.query.filter(Note.title = 'flask').order_by(Note.timestamp).all()
limit(limit)根据指定的值限制查询数量
Comment.query.limit(5).all()
group_by()根据条件对记录进行分组
from sqlalchemy import func
Comment.query.with_entities(Comment,func.count('*').label('cnt')).group_by(Comment.post_id).all()
offset(offset)根据指定偏移量查询结果
Comment.query.offset(2).limit(5).all()
随机查询10个记录
Comment.query.order_by(func.random()).limit(10)
问 AI(只依据本文回答)
输入你的问题,AI 只根据当前段落和全篇上下文回答。
本文批注(0)