Skip to content

Return type of item id from session.exec is int | None. How can I make it int. #1486

Discussion options

You must be logged in to vote

Yes, creating a separate model with required id field is a conventional approach.

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/
More specifically: https://sqlmodel.tiangolo.com/tutorial/fastapi/…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
2 participants
Converted from issue

This discussion was converted from issue #282 on August 11, 2025 21:25.