python-3.x SQLModel:如何加载特定的列?

sy5wg1nm  于 2023-04-22  发布在  Python
关注(0)|答案(1)|浏览(124)

我尝试通过以下方法从表中加载特定列:

from sqlalchemy.orm import load_only
from sqlmodel import (Field, Session, SQLModel, create_engine, select)
from models import ( Tx )

engine = create_engine(url, echo=True)

        with Session(engine) as session:
            results = session.exec(select(Tx.Id, Tx.party, Tx.time)
                                   .order_by(Tx
                                             .time
                                             .desc())
                                   ).all()

            myResults = []
            
            for result in results:
                myResults.append(result.toDict())

然而,返回Row类,然后我不能运行toDict(),因为通常我会返回具有该方法的Tx类。希望它清楚我想要什么,我不期望Row类。
然后我尝试使用sqlalchemy方法,然而,这似乎不太好用,因为它返回所有列,不管我过滤的是什么:

from sqlalchemy.orm import load_only
from sqlmodel import (Field, Session, SQLModel, create_engine, select)
from models import ( Tx )

engine = create_engine(url, echo=True)

        with Session(engine) as session:
            results = session.exec(select(Tx)
                                   .options(load_only("id", "party", "time")))
                                   .order_by(Tx
                                             .time
                                             .desc())
                                   ).all()
            myResults = []
            
            for result in results:
                myResults.append(result.toDict())
toe95027

toe950271#

你只需要获取results并将其传递给 jsonable_encoder 方法。

因此,输入results是一个包含类型为sqlalchemy.engine.row.Row的对象的列表,输出将是一个包含类型为dict的对象的列表。

from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse

with Session(engine) as session:
    results = session.exec(select(Tx.id,Tx.party,Tx.time)).order_by(Tx.time.desc()).all()
json_compatible = jsonable_encoder(results)
return JSONResponse(status_code=200, content=json_compatible)

相关问题