How to map query results to objects? #1315
-
First Check
Commit to Help
Example Codefrom sqlmodel import Field, SQLModel, Session, col, select
from sqlalchemy import func
class Person(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
first_name: str
last_name: str
age: int | None = None
# Note: this is NOT a table
class QueryResult(SQLModel):
full_name: str
person_age: int | None = None
with Session(engine) as session:
query = (
select(
func.concat(Person.first_name, Person.last_name).label('full_name'),
col(Person.age).label('person_age')
)
.select_from(Person)
)
results = session.exec(query).all()
print(results) DescriptionSupposed that I have 2 models, The I know that I can do it manually by looping through the Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.22 Python Version3.11.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Validate res = [QueryResult.model_validate({"full_name": row[0], "person_age": row[1]} for row in results)] |
Beta Was this translation helpful? Give feedback.
Validate
results
withQueryResult
model.Something like