Access Relationship (from table model) from Read Model #1493
-
First Check
Commit to Help
Example Codefrom typing import Optional, List
from sqlmodel import Field, SQLModel, Relationship
# M2M
class HeroPowerLink(SQLModel, table=True):
hero_id: Optional[int] = Field(
default=None, foreign_key="hero.id", primary_key=True
)
power_id: Optional[int] = Field(
default=None, foreign_key="power.id", primary_key=True
)
class PowerBase(SQLModel):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
description: str
class Power(PowerBase, table=True):
heroes: List["Hero"] = Relationship(back_populates="powers", link_model=HeroPowerLink)
# =====
class HeroBase(SQLModel):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
class Hero(HeroBase, table=True):
powers: List["Power"] = Relationship(back_populates="heroes", link_model=HeroPowerLink)
class HeroCreate(HeroBase):
type: str
class HeroRead(HeroBase):
id: int
# HOW TO ACCESS `powers` HERE? DescriptionFollowing from the tutorial I've created a similar model structure. As mentioned this kind of relationship fields should be added on both sided in the table model, that is The problem is that now from my In this case
I think I'm missing something here. Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.6 Python Version3.8.9 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
I guess you already tried this?
But there is a caveat: by the time the
|
Beta Was this translation helpful? Give feedback.
-
Also something like this is an alternative solution, don't know how to say it with the link table though: class Power(PowerBase, table=True):
heroes: List["Hero"] = Relationship(back_populates="powers",
sa_relationship_kwargs={"primaryjoin": "Power.hero_id==Hero.id", "lazy": "joined"}) Such SQLAlchemy relationship & link table seems to be discussed in #89 for other reasons. |
Beta Was this translation helpful? Give feedback.
-
Good to know, thanks! But |
Beta Was this translation helpful? Give feedback.
-
Ah, you already mentioned that, sorry, my bad. |
Beta Was this translation helpful? Give feedback.
-
Yes, the solution suggested by @antont also works:
|
Beta Was this translation helpful? Give feedback.
I guess you already tried this?
But there is a caveat: by the time the
powers
attribute is accessed in your code, your session might already be closed. You can solve this by loadingpowers
up front. This worked for me: