How to build a relationship with yourself #691
Unanswered
Leewinner1
asked this question in
Questions
Replies: 2 comments
-
If 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 |
Beta Was this translation helpful? Give feedback.
0 replies
-
In addition to @nayaverdier answer, here is another example using a one-to-many relationship to create a tree: class Node(SQLModel, table=True):
uuid: UUID = Field(
default_factory=uuid4,
primary_key=True,
index=True,
nullable=False,
)
parent_uuid: UUID | None = Field(
foreign_key='node.uuid', # notice the lowercase "n" to refer to the database table name
default=None,
nullable=True
)
parent: Optional['Node'] = Relationship(
back_populates='children',
sa_relationship_kwargs=dict(
remote_side='Node.uuid' # notice the uppercase "N" to refer to this table class
)
)
children: list['Node'] = Relationship(back_populates='parent', sa_relationship_kwargs={"lazy": "joined", "join_depth": 2}) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
First Check
Commit to Help
Example Code
Description
i created a p_id field in the Category model class, associated with its own id.
And I also define a child to have a relationship with the Category itself
What I want to do is implement Category.p_id.name to find my own "name"
Operating System
Windows
Operating System Details
No response
SQLModel Version
0.0.11
Python Version
3.12
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions