Return type of item id from session.exec is int | None
. How can I make it int
.
#1486
-
First Check
Commit to Help
Example Codefrom sqlalchemy.exc import NoResultFound
from sqlmodel import Field, Session, SQLModel, create_engine
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
class Person(SQLModel):
id: int | None = Field(default=None, primary_key=True, index=True)
name: str
def add_person():
with Session(engine) as session:
john = Person(name="John")
session.add(john)
session.commit()
def get_person_or_404(id: int) -> Person:
with Session(engine) as session:
person = session.get(Person, id)
if not person:
raise NoResultFound("Person not found")
return person
def main():
create_db_and_tables()
add_person()
person = get_person_or_404(1)
print(f"person.id: {person.id}")
if __name__ == "__main__":
main() DescriptionIf get person from db and db always returns the person with the id (type: Hence, the type of How I type the Thanks. Operating SystemLinux Operating System DetailsUbuntu 21.10 SQLModel Version0.0.6 Python Version3.10.2 Additional Context |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
As of now, I am creating a new class and def get_product(session: Session, id: PositiveInt) -> ProductDbRead | None:
return cast(ProductDbRead, session.get(Product, id)) |
Beta Was this translation helpful? Give feedback.
-
Yes, creating a separate model with required class PersonBase(SQLModel):
name: str
class Person(PersonBase):
id: int | None = Field(default=None, primary_key=True, index=True)
class PersonRead(PersonBase):
id: int
...
def get_person_or_404(id: int) -> PersonRead:
with Session(engine) as session:
person = session.get(Person, id)
if not person:
raise NoResultFound("Person not found")
return PersonRead.model_validate(person, from_attributes=True) This is explained here: https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/ |
Beta Was this translation helpful? Give feedback.
Yes, creating a separate model with required
id
field is a conventional approach.This is explained here: https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/
More specifically: https://sqlmodel.tiangolo.com/tutorial/fastapi/…