How to inherit Class with ‘sa_column’ in a proper way? #906
-
First Check
Commit to Help
Example CodefromsqlmodelimportSQLModel, Field, RelationshipfromdatetimeimportdatetimefromsqlalchemyimportColumn, JSONclassReportItemBase(SQLModel): id: int=Field( primary_key=True, index=True, nullable=False, sa_column_kwargs={"autoincrement": True}, ) pub_date: datetime|Nonerisk_level: intfull_content: dict|None=Field(sa_column=Column(JSON)) classReportItem(ReportItemBase, table=True): __tablename__="reportitem_json"report_rule: "ReportRule"=Relationship(back_populates="rule_risk_items") classArchivedItem(ReportItemBase, BaseIntIDModel, table=True): __tablename__="reportitem_archived"report_rule: "ReportRule"=Relationship(back_populates="archived_items")DescriptionWhen I run fastapi, i get an error "sqlalchemy.exc.ArgumentError: Column object 'full_content' already assigned to Table 'reportitem_json'". I've read SQLAlchemy's doc Mapping Class Inheritance Hierarchies and still have no idea. Why this happen and what should i do to fix it? Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.16 Python Version3.10.12 Additional ContextSQLAlchemy 2.0.29 |
BetaWas this translation helpful?Give feedback.
Replies: 4 comments 3 replies
-
You are right there is a strange behaviour here but what you can actually do is to use This should work as expected: classReportItemBase(SQLModel): ... full_content: Optional[dict] =Field(None, sa_type=JSON) |
BetaWas this translation helpful?Give feedback.
-
邮件已收到,我会尽快回复~【自动回复】 |
BetaWas this translation helpful?Give feedback.
-
I am facing a similar problem but I use the onupdate attr from Column. I get this error sqlalchemy.exc.ArgumentError: Column object 'updated_at' already assigned to Table 'user'. Is there a solution to this? |
BetaWas this translation helpful?Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
After Python 3.11, you can use TypedDict/NotRequired from typing to deal with sa_type=JSON properly, supporting Swagger Doc schema, like: classCustomer(TypedDict): name: Annotated[str, Field(description="Name")] tel: Annotated[NotRequired[str|None], Field(description="Tel")] =NoneclassFactory(SQLModel): customers: Annotated[list[Customer], Field(sa_type=JSON, description="Customer list")] = [] |
BetaWas this translation helpful?Give feedback.
You are right there is a strange behaviour here but what you can actually do is to use
sa_typeinstead ofsa_column.This should work as expected: