How to inherit Class with ‘sa_column’ in a proper way? #906
-
First Check
Commit to Help
Example Codefrom sqlmodel import SQLModel, Field, Relationship
from datetime import datetime
from sqlalchemy import Column, JSON
class ReportItemBase(SQLModel):
id: int = Field(
primary_key=True,
index=True,
nullable=False,
sa_column_kwargs={"autoincrement": True},
)
pub_date: datetime | None
risk_level: int
full_content: dict | None = Field(sa_column=Column(JSON))
class ReportItem(ReportItemBase, table=True):
__tablename__ = "reportitem_json"
report_rule: "ReportRule" = Relationship(back_populates="rule_risk_items")
class ArchivedItem(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 |
Beta Was this translation helpful? Give feedback.
Replies: 3 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: class ReportItemBase(SQLModel):
...
full_content: Optional[dict] = Field(None, sa_type=JSON) |
Beta Was this translation helpful? Give feedback.
-
邮件已收到,我会尽快回复~【自动回复】
|
Beta Was 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? |
Beta Was this translation helpful? Give feedback.
You are right there is a strange behaviour here but what you can actually do is to use
sa_type
instead ofsa_column
.This should work as expected: