Skip to content

How to build a relationship with yourself #691

Discussion options

You must be logged in to vote

If p_id is meant to be a parent_id on the other side of the child relationship, you can do something like this (assuming a parent category can have multiple child categories):

    p_id: int | None = Field(None, foreign_key="tb_category.id")

    parent: Optional["Category"] = Relationship(back_populates="children", sa_relationship_kwargs={"remote_side": lambda: Category.id})
    children: list["Category"] = Relationship(back_populates="parent")

Then you can use some_category.parent.name.

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
3 participants