Flask-SQLAlchemy 3.x最新语法:查询含指定关键词的记录
Flask-SQLAlchemy 3.x 实现包含关键词的内容查询
问题分析
你的代码存在两个核心问题导致查询失败:
- LIKE查询缺少通配符:直接使用
Post.content.like(form.search.data)只会匹配与关键词完全一致的内容,无法匹配包含关键词的记录 - 结果获取方式错误:
scalar()仅返回第一条匹配结果,若要获取所有符合条件的记录,需使用scalars().all()
修正后的代码
搜索函数
@app.route('/search', methods=['POST']) def search(): form = SearchForm() if form.validate_on_submit(): # 构造包含通配符的关键词,实现包含匹配 search_keyword = f"%{form.search.data}%" # 执行查询并获取所有匹配记录 post_search = db.session.execute( db.select(Post).where(Post.content.like(search_keyword)) ).scalars().all() # 可打印结果数量验证 print(f"找到 {len(post_search)} 条匹配记录") return render_template('search.html', form=form, search_results=post_search)
注意:修正模型代码的缩进
你的Post模型存在缩进错误,需调整为:
class Post(db.Model): __tablename__ = "posts" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text(1000), nullable=False) date_posted = db.Column(db.DateTime, default=datetime.now()) user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
关键说明
- 通配符使用:
%是SQL标准的通配符,%关键词%表示匹配任意位置包含该关键词的内容;若只需前缀/后缀匹配,可使用关键词%或%关键词 - 查询执行:
db.session.execute(db.select(...))是Flask-SQLAlchemy 3.x官方推荐的替代Model.query的查询语法 - 结果处理:
scalars()返回查询结果的ORM对象迭代器,.all()将其转换为列表,方便在模板中遍历展示
内容的提问来源于stack exchange,提问作者kenpino
相关产品推荐
相关产品推荐

