SQLModel JSON schema missing relationship fields #1438
-
First Check
Commit to Help
Example Codeclass Team(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
class Hero(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
team_id: int = Field(foreign_key="team.id")
team: Team = Relationship()
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
SQLModel.metadata.create_all(engine)
print(Hero.model_json_schema()) DescriptionI'm running into a limitation with SQLModel and would appreciate some clarification or guidance. When I call Hero.model_json_schema(), the generated JSON schema doesn't include the team relationship field. Since Team is a SQLModel (and therefore a valid Pydantic model), I'd naturally expect it to appear in the schema. Questions
Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.24 Python Version3.12.1 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The solution is to create new model (use inheritance to reduce duplication) and use it as response model: class HeroBase(SQLModel):
id: int | None = Field(default=None, primary_key=True)
name: str
class Hero(HeroBase, table=True):
team_id: int = Field(foreign_key="team.id")
team: Team = Relationship()
class HeroPublic(HeroBase):
team: Team Read more: https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/#dont-include-all-the-data |
Beta Was this translation helpful? Give feedback.
The solution is to create new model (use inheritance to reduce duplication) and use it as response model:
Read more: https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/#dont-include-all-the-data