First Check
Commit to Help
Example Code
from 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()
Description
If get person from db and db always returns the person with the id (type: int). However person returned by person = get_person_or_404(1) has person with id optional.
Hence, the type of person.id is int | None even though it is returned from DB.
How I type the get_person_or_404 function to let it know that id from Person class is int and not int | None.
Thanks.
Operating System
Linux
Operating System Details
Ubuntu 21.10
SQLModel Version
0.0.6
Python Version
3.10.2
Additional Context

First Check
Commit to Help
Example Code
Description
If get person from db and db always returns the person with the id (type:
int). However person returned byperson = get_person_or_404(1)has person with id optional.Hence, the type of
person.idisint | Noneeven though it is returned from DB.How I type the
get_person_or_404function to let it know that id fromPersonclass isintand notint | None.Thanks.
Operating System
Linux
Operating System Details
Ubuntu 21.10
SQLModel Version
0.0.6
Python Version
3.10.2
Additional Context