Skip to content

Mypy errors: Incompatible type for optional ids & Incompatible type for SQLModel attribute in expression #1491

Answered by YuriiMotov
javivdm asked this question in Questions
Discussion options

You must be logged in to vote

The has no attribute "in_" error is fixed by using col as @danielunderwood pointed.

As for incompatible type "Optional[int]"; expected "int" error, you can either make the input parameter of format_id optional and then assert that it's not None inside:

def format_id(id: int | None):
    assert id is not None
    return f"{id:04d}"

Or, create one more model and re-define the type of id field:

class HeroBase(SQLModel):
    name: str

class HeroDB(HeroBase, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)

class Hero(HeroBase):
    id: int

Then after fetching the object from DB, convert it to Hero:

    session.refresh(hero_1)
    hero_1_read = Hero.model_validate(he…

Replies: 10 comments

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
0 replies
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
0 replies
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
0 replies
Comment options

You must be logged in to vote
0 replies
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
6 participants
Converted from issue

This discussion was converted from issue #267 on August 12, 2025 09:14.