Dave Cook
Dave Cook

Reputation: 717

Python SQLAlchemy 2.0 non required field types using dataclass_transform

I have just installed SQLAlchemy 2.0 on a new project and I am trying to make my models as type-safe as possible.

By using @typing_extensions.dataclass_transform, I have been able to achieve most of what I want to achieve in terms of type checking, however all fields are currently being marked as not required.

For example:


@typing_extensions.dataclass_transform(kw_only_default=True)
class Base(DeclarativeBase):
    pass

class TestModel(Base):
    __tablename__ = "test_table"
    name: Mapped[str]
    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    external_id: Mapped[int] = mapped_column(
        ForeignKey("external.id"), nullable=False
    )

def test_test_model(session: Session) -> None:
    TEST_NAME = "name"
    external = External()
    session.add(external)
    session.commit()
    model1 = TestModel() # Intellisense shows error because "name" is required

    model2 = TestModel(name=TEST_NAME, external_id=external.id). # no error
    session.add(model2)
    session.commit() # model commits successfully

    model3 = TestModel(name=TEST_NAME) # No intellisense error, despite "external_id" being required
    session.add(model3)
    session.commit(). # error when saving because of missing "external_id"

In the example above, how can I set the type of external_id to be required?

Upvotes: 2

Views: 295

Answers (1)

Dave Cook
Dave Cook

Reputation: 717

I've got this working. With this configuration, I get the errors I wanted:

@typing_extensions.dataclass_transform(
    kw_only_default=True, field_specifiers=(mapped_column,)
)
class Base(DeclarativeBase):
    pass

Upvotes: 2

Related Questions