Can't return result from session.exec directly (have to assign to an intermediate variable)? #984
Replies: 2 comments
-
p.s., I suppose the Pydantic types are being constructed from the result data -- maybe that's the answer. I wasn't expecting that to be necessary since I passed the type to the embedded select(...) (so maybe they don't come back as my custom Pyndatic types from session.exec(...)?) |
Beta Was this translation helpful? Give feedback.
0 replies
-
There shouldn't be any difference. Could you provide MRE? from typing import List
from fastapi import FastAPI
from sqlalchemy import StaticPool
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Organization(SQLModel, table=True):
id: int = Field(default=None, primary_key=True)
name: str
# Create an in-memory SQLite database
connect_args = {"check_same_thread": False}
engine = create_engine(
"sqlite:///:memory:", connect_args=connect_args, poolclass=StaticPool
)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
session.add(Organization(name="Example Org"))
session.add(Organization(name="Example Org 2"))
session.add(Organization(name="Example Org 3"))
session.commit()
app = FastAPI()
@app.get("/organizations/")
def read_organizations() -> List[Organization]:
with Session(engine) as session:
return session.exec(select(Organization)).all() |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
I now know from the examples (after looking more) that you always assign the result from session.exec calls to a var of some Pydantic model type before returning anything from a function, but I'm still curious why the former doesn't work below (but the latter does). Can I get some info (maybe which library leads to this behavior, and where I can look to learn more about why this is needed, or what I can search for to read some more, since they appeared functionally equivalent to me).
vs.
Description
Just trying to get back all "organizations" instead of a single one. Something about my code structure in the former code is maybe returning from session.exec(...) before it has data, or is breaking it (but this is synchronous, so I wouldn't think that's the case)? I noticed you always assign to an intermediate variable before returning anything, so hopefully you know why/can point me to something I can read/Google about.
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.18
Python Version
3.12
Additional Context
Thank you! Sorry if this is just a dumb variable scope/Python code structure issue -- I'm a bit rusty atm.
Beta Was this translation helpful? Give feedback.
All reactions