sqlmodel icon indicating copy to clipboard operation
sqlmodel copied to clipboard

Optional ID value for auto-increment causes type errors when retrieving from database

Open davecook88 opened this issue 2 years ago • 3 comments

First Check

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

Commit to Help

  • [X] I commit to help with one of those options 👆

Example Code

class MyModel(DBModel, table=True):

    id: Optional[int] = Field( primary_key=True)

Description

Thanks for the great library. I'm just

If I have a model like this:

class MyModel(DBModel, table=True):

    id: Optional[int] = Field( primary_key=True)

Then when saving new records to the database, the ID is automatically assigned, which is great.

However, when I retrieve the model like this I get type errors

model = session.get(MyModel, 1)
id: int = model.id  # ID may be None error

Is there a way to auto-assign my IDs but also have the ID type defined when retrieving saved records?

Operating System

macOS

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.10.4

Additional Context

No response

davecook88 avatar Jun 22 '22 18:06 davecook88

I don't think what you say happens - if you get the object like that, the id will be 1 not None

antont avatar Jun 24 '22 06:06 antont

add line assert model.id is not None before declare variable id id = model.id

phi-friday avatar Jun 24 '22 23:06 phi-friday

model = session.get(MyModel, 1)
id: int = model.id  # ID may be None error

The issue here isn't that id may be None, it's that model may be None, as session.get will return None if no entry is found - if you're using VSCode you can see this by hovering over model:

image

You should add a check to deal model being None before trying to access id and that will solve the problem:

model = session.get(MyModel, 1)
if model is None:
    raise sqlalchemy.exc.NoResultFound

model.id  # no more type warning here

Hope that helps!

RobertRosca avatar Jul 01 '22 11:07 RobertRosca