First Check
Commit to Help
Example Code
from 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?
Description
Following from the tutorial I've created a similar model structure.
The model Power and Hero are linked via and M2M model HeroPowerLink.
As mentioned this kind of relationship fields should be added on both sided in the table model, that is Hero and Power.
The problem is that now from my HeroRead (what's returned to the user) I want to include the field powers, that is a list of Powers objects.
In this case HeroRead inherits directly form HeroBase (the documentation discourage to inherit from table models) and of course it can't see the powers field.
If I declare the powers in the base model I get
sqlalchemy.exc.InvalidRequestError: Mapper 'mapped class Hero->hero' has no property 'episodes'
I think I'm missing something here.
How can I access powers from the HeroRead?
Operating System
macOS
Operating System Details
No response
SQLModel Version
0.0.6
Python Version
3.8.9
Additional Context
No response
First Check
Commit to Help
Example Code
Description
Following from the tutorial I've created a similar model structure.
The model
PowerandHeroare linked via and M2M modelHeroPowerLink.As mentioned this kind of relationship fields should be added on both sided in the table model, that is
HeroandPower.The problem is that now from my
HeroRead(what's returned to the user) I want to include the fieldpowers, that is a list ofPowers objects.In this case
HeroReadinherits directly formHeroBase(the documentation discourage to inherit from table models) and of course it can't see thepowersfield.If I declare the
powersin the base model I getI think I'm missing something here.
How can I access
powersfrom theHeroRead?Operating System
macOS
Operating System Details
No response
SQLModel Version
0.0.6
Python Version
3.8.9
Additional Context
No response