sqlmodel icon indicating copy to clipboard operation
sqlmodel copied to clipboard

✨Properly support inheritance of Relationship attributes

Open earshinov opened this issue 1 year ago • 0 comments

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.

earshinov avatar Apr 08 '24 12:04 earshinov