Skip to content

Many to many relationship between a table and itself #1456

Answered by daniil-berg
joaopfg asked this question in Questions
Discussion options

You must be logged in to vote

What you can already do is set up relationships back-and-forth between the Node and Edge tables, such that

  1. every Node has a list of all outgoing edges and a list of all incoming edges and
  2. every Edge has references to its "to"- and "from"-nodes.

Here is an example:

from typing import Optional

from sqlmodel import Field, Relationship, SQLModel


class Node(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    edges_out: list["Edge"] = Relationship(
        back_populates="from_node",
        sa_relationship_kwargs={
            "foreign_keys": "Edge.from_node_id",
            "lazy": "selectin",
        },
    )
    edges_in: list["Edge"] = Relationship(…

Replies: 6 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
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
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
feature New feature or request
7 participants
Converted from issue

This discussion was converted from issue #545 on August 06, 2025 18:14.