Optional ID value for auto-increment causes type errors when retrieving from database #1474
-
First Check
Commit to Help
Example Codeclass MyModel(DBModel, table=True):
id: Optional[int] = Field( primary_key=True) DescriptionThanks for the great library. I'm just If I have a model like this:
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
Is there a way to auto-assign my IDs but also have the ID type defined when retrieving saved records? Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.6 Python Version3.10.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I don't think what you say happens - if you get the object like that, the id will be |
Beta Was this translation helpful? Give feedback.
-
add line |
Beta Was this translation helpful? Give feedback.
-
model = session.get(MyModel, 1)
id: int = model.id # ID may be None error The issue here isn't that You should add a check to deal model = session.get(MyModel, 1)
if model is None:
raise sqlalchemy.exc.NoResultFound
model.id # no more type warning here Hope that helps! |
Beta Was this translation helpful? Give feedback.
The issue here isn't that
id
may beNone
, it's thatmodel
may beNone
, assession.get
will returnNone
if no entry is found - if you're using VSCode you can see this by hovering overmodel
:You should add a check to deal
model
beingNone
before trying to accessid
and that will solve the problem:Hope that helps!