ITADN

Binds not working when using SQLModel as model class

#1407Closedsvalo 创建于 2025-11-04
S
svalocommented
I'm using SQLModel to define my models and Flask-SQLAlchemy to query them. When adding binds in the mix, queries are routed to the default bind regardless of the __bind_key__ set. As SQLModel extends SQLAlchemy I exptected it to work. Is this scenario supported? Should I do something special? ## Example ```python3 import sqlite3 from flask import Flask from flask_sqlalchemy import SQLAlchemy from sqlmodel import SQLModel, Field, select class MyDB(SQLModel): pass db = SQLAlchemy(model_class=MyDB) class Nea(MyDB, table=True): __bind_key__ = "nea" id: int | None = Field(default=None, primary_key=True) name: str permid: int provid: int class Other(MyDB, table=True): __bind_key__ = "other" id: int | None = Field(default=None, primary_key=True) data: str def create_app(): app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///default.db" app.config["SQLALCHEMY_BINDS"] = { "nea": "sqlite:///nea.db", "other": "sqlite:///other.db", } db.init_app(app) with app.app_context(): SQLModel.metadata.create_all(db.engine) for bind, engine in db.engines.items(): SQLModel.metadata.create_all(engine) return app def build_query(name=None): stmt = select(Nea) if name: stmt = stmt.where(Nea.name.ilike(f"%{name}%")) return stmt app = create_app() con = sqlite3.connect('instance/nea.db') cur = con.cursor() cur.execute("INSERT INTO nea(name,permid,provid) VALUES('nea1', 11, 21)") con.commit() con = sqlite3.connect('instance/default.db') cur = con.cursor() cur.execute("INSERT INTO nea(name,permid,provid) VALUES('default', 12, 22)") con.commit() with app.app_context(): stmt = build_query() rows = db.session.execute(stmt).mappings().all() for r in rows: print(dict(r)) ``` Environment: - Python version: 3.13.1 - annotated-types==0.7.0 - blinker==1.9.0 - click==8.3.0 - flask==3.1.2 - flask-sqlalchemy==3.1.1 - greenlet==3.2.4 - itsdangerous==2.2.0 - jinja2==3.1.6 - markupsafe==3.0.3 - pydantic==2.12.3 - pydantic-core==2.41.4 - sqlalchemy==2.0.44 - sqlmodel==0.0.27 - typing-extensions==4.15.0 - typing-inspection==0.4.2 - werkzeug==3.1.3 If I avoid the `db.session` and instead use `db.Session(bind=db.get_engine(bind=Nea.__bind_key__))` as session it works, but I loose all the nice features of `db.session` and I need to deal with the session myself.
关闭于 2025-11-04 3 条评论