sqlmodel
sqlmodel copied to clipboard
Optional ID value for auto-increment causes type errors when retrieving from database
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
I don't think what you say happens - if you get the object like that, the id will be 1
not None
add line assert model.id is not None
before declare variable id id = model.id
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
:
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!