'SQLModel: how to load specific columns?
I tried to load specific columns from a table via the following method:
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())
However returns Row class which then I can't run toDict()
since normally I get back Tx
class that has that method. Hope it is clear what I want here, I did not expect Row class.
So then I try using the sqlalchemy method, however, this does not seem to work well, as it returns ALL columns, regardless of what I filter for:
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())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|