Skip to content

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

Discussion options

You must be logged in to vote
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!

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@YuriiMotov
Comment options

Answer selected by YuriiMotov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
5 participants
Converted from issue

This discussion was converted from issue #365 on August 11, 2025 03:34.