[Python] SQLModel relationship through two foreign keys

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

    Can I make a relationship with table C, which contains a foreign key to table B, which contains a foreign key to table A, from C to A? Something like the following:

    class A(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    b_id: int | None = Field(default=None, foreign_key="b.id")

    b: 'B' = Relationship(back_populates='as')
    c: 'C' = Relationship() # Somehow have this automatically populated through b.c_id?

    class B(SQLModel, table=True):
    id: id | None = Field(default=None, primary_key=True)
    c_id: int | None = Field(default=None, foreign_key='c.id)

    as: list[A] = Relationship(back_populates='b')
    c: 'C' = Relationship(back_populates='bs')

    class C(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)

    bs: list = Relationship(back_populates='c')


    I'm not even sure where to start with this. I tried just doing it and it threw an error for no foreign keys for A.c.

    Continue reading...

Compartilhe esta Página