sqlmodel
sqlmodel copied to clipboard
✨Properly support inheritance of Relationship attributes
Please see the test I added:
class CreatedUpdatedMixin(SQLModel):
created_by_id: Optional[int] = Field(default=None, foreign_key="user.id")
created_by: Optional[User] = Relationship(
sa_relationship=declared_attr(
lambda cls: relationship(User, foreign_keys=cls.created_by_id)
)
)
class Asset(CreatedUpdatedMixin, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
Given how the test model is defined and without the proposed fix, the test fails with:
with Session(engine) as session:
asset = session.exec(select(Asset)).one()
> assert asset.created_by.name == "John"
E AttributeError: 'Asset' object has no attribute 'created_by'
That is, a Relationship defined in the base model is not recognized as a relationship in the child.