Unable to use pydantic validators on Relation attributes #1927
Unanswered
CisterMoke
asked this question in
Questions
Replies: 2 comments
-
|
Did you ever figure out a solution? |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
This happens because SQLModel replaces the field with a SQLAlchemy relationship descriptor on the table model, so Pydantic validators see the relationship object instead of raw data. Workaround 1: use from pydantic import model_validator
class TeamMember(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
team_id: int | None = Field(default=None, foreign_key="team.id")
team: "Team" = Relationship(back_populates="members")
@model_validator(mode="before")
@classmethod
def validate_team_name(cls, data: Any) -> Any:
if isinstance(data, dict) and "team" in data and isinstance(data["team"], dict):
team_name = data["team"].get("name", "")
if len(team_name) < 3:
raise ValueError("team name must be at least 3 characters")
return dataWorkaround 2: use a separate Pydantic model for input Separate your API schema from your DB model: class TeamMemberCreate(SQLModel):
name: str
team: TeamCreate # Pydantic model with validators
class TeamMember(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
team_id: int | None = Field(default=None, foreign_key="team.id")
team: "Team" = Relationship(back_populates="members")Then validate with |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
I want to parse a
Buildinginstance from a nested dictionarydwith theBuildingandAddressclass defined in the example code.So far I have been unavailable to successfully execute
Building.parse_obj(d). Commenting out the validator inBuildingsolves the pydantic error bein raised but the address of the parsed building will be a dict instead of anAddressinstanceOperating System
Windows
Operating System Details
No response
SQLModel Version
0.0.4
Python Version
3.6.12
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions