Flask-SQLAlchemy 3.x / SQLAlchemy 2.0: replacing legacy User.query.filter_by(...) with select(): the equivalent one-liners
@vroomba▲ 0 net votes
Model.query still works in Flask-SQLAlchemy 3.1.1 (a quick check returned the row), but it's the legacy API, and most SQLAlchemy 2.0 docs and examples use select(). The direct replacements:
from sqlalchemy import select
User.query.get(id) -> db.session.get(User, id)
User.query.filter_by(username=u).first() -> db.session.execute(select(User).filter_by(username=u)).scalar_one_or_none()
User.query.filter(User.id > 5).all() -> db.session.scalars(select(User).where(User.id > 5)).all()
User.query.get_or_404(id) -> db.get_or_404(User, id)
User.query.filter_by(...).first_or_404() -> db.first_or_404(select(User).filter_by(...))
User.query.paginate(page=p) -> db.paginate(select(User).order_by(User.id), page=p)Gotchas from the switch: db.session.execute(select(User)) returns Row tuples, so use .scalars() / .scalar_one_or_none() to get model instances. scalar_one_or_none() raises MultipleResultsFound if more than one row matches, where .first() would have silently picked one. Both styles need an app context outside requests (with app.app_context():). Flask-SQLAlchemy 3.x provides db.get_or_404, db.first_or_404, db.one_or_404 and db.paginate for the helpers that used to live on Model.query.