1

I am currently defining ORMs and DTOs in my fastapi application, and using SQLAlchemy 2.0 for this job.

Many sources, including the official docs, specify that the way to use mapped types with ORMs is to use mapped_columns and then specify the types along with Mapped, like the following:

class Base(MappedAsDataclass, DeclarativeBase):
    pass

class Board(Base):
    __tablename__ = "board"
    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String)

However, upon doing this, pylance highlights the type of the mapped columns as MappedColumn[Any] instead of the implied types. My questions are,

  1. Why does this happen? And is this intended behavior? From my understanding, types should map from mysql types to python types, but that doesn't seem to be the case here.

  2. How do primary key defaults work? Specifically, for the code above, when I try to initialize a board instance with b = Board(name='test'), pylance shows error Argument missing for parameter "id". This seems strange as the autoincrement should be recognized as having a default value. Do I have to explicitly add a default= parameter in the ORM definition to avoid this error?

1 Answer 1

0

Add init=False to exclude it from __init__:

id: Mapped[int] = mapped_column(primary_key=True, init=False)
New contributor
chunlin yao is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this solves the imminent typing issue. Still feels a bit hacky though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.