Sqlmodel 0.0.14 throws strange Pydantic error for relationships when adding another field #723
Answered
by
nazmi
junoriosity
asked this question in
Questions
-
First Check
Commit to Help
Example Codefrom typing import List, Optional
from sqlmodel import Field, Relationship, SQLModel
class HeroTeamLink(SQLModel, table=True):
team_id: Optional[int] = Field(
default=None, foreign_key="team.id", primary_key=True
)
hero_id: Optional[int] = Field(
default=None, foreign_key="hero.id", primary_key=True
)
class Team(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
headquarters: str
heroes: List["Hero"] = Relationship(back_populates="teams", link_model=HeroTeamLink)
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
teams: List[Team] = Relationship(back_populates="heroes", link_model=HeroTeamLink)
class HeroOut(Hero):
is_new: bool = Field(default=False) DescriptionThis is the result we get
Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.14 Python Version3.12 Additional ContextWe use Pydantic version 2.5.2 |
Beta Was this translation helpful? Give feedback.
Answered by
nazmi
Dec 4, 2023
Replies: 1 comment 1 reply
-
If you want to inherit from a model, starts with a Base that shares common attributes. from typing import List, Optional
from sqlmodel import Field, Relationship, SQLModel
class HeroBase(SQLModel):
name: str
secret_name: str
age: Optional[int] = None
class Hero(HeroBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
teams: List[Team] = Relationship(back_populates="heroes")
class HeroRead(HeroBase):
id: int
is_new: bool = False Only the ones with table==True are created. You should put is_new inside Hero, otherwise, this attribute isn't in the database. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
YuriiMotov
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want to inherit from a model, starts with a Base that shares common attributes.
Only the ones with table==True are created. You should put is_new inside Hero, otherwise, this attribute isn't in the database.