Skip to content

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

@jd-solanki

Description

@jd-solanki

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

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

Screenshot from 2022-03-24 13-38-18

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions