FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Fix issue with relationship dict by Tesla2000 · Pull Request #1874 · fastapi/sqlmodel · GitHub

Repository navigation

Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
6 changes: 5 additions & 1 deletion sqlmodel/_compat.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,11 @@ def sqlmodel_validate(
# Get and set any relationship objects
if is_table_model_class(cls):
for key in new_obj.__sqlmodel_relationships__:
value = getattr(use_obj, key, Undefined)
value = (
use_obj.get(key, Undefined)
if isinstance(use_obj, dict)
else getattr(use_obj, key, Undefined)
)
if value is not Undefined:
setattr(new_obj, key, value)
return new_obj
Expand Down
67 changes: 67 additions & 0 deletions tests/test_relationship_dict.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""
Regression test for: model_validate with a dict containing relationship keys
silently drops the relationship data.

Root cause: sqlmodel_validate in _compat.py uses getattr(use_obj, key, Undefined)
to extract relationship values. When use_obj is a dict, getattr finds no attribute
named e.g. "heroes", returning Undefined, so relationships are never set.

Fix: use dict.get() when use_obj is a dict instance.
"""

from sqlalchemy.orm import selectinload
from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select


def test_model_validate_dict_populates_relationships():
"""Relationships passed as dict keys to model_validate should be set."""

class Team(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
heroes: list["Hero"] = Relationship(back_populates="team")

class Hero(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 | None = Relationship(back_populates="heroes")

heroes = [Hero(name="Deadpond"), Hero(name="Spider-Boy")]
team = Team.model_validate({"name": "Z-Force", "heroes": heroes})

assert len(team.heroes) == 2, (
"model_validate with a dict should populate relationship fields"
)


def test_model_validate_dict_relationships_persisted():
"""Relationships set via model_validate dict should be saved and loadable."""

class Team(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
heroes: list["Hero"] = Relationship(back_populates="team")

class Hero(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 | None = Relationship(back_populates="heroes")

engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)

heroes = [Hero(name="Deadpond"), Hero(name="Spider-Boy")]
team = Team.model_validate({"name": "Z-Force", "heroes": heroes})

with Session(engine) as session:
session.add(team)
session.commit()

with Session(engine) as session:
loaded = session.exec(
select(Team).options(selectinload(Team.heroes)) # type: ignore[arg-type]
).first()
assert loaded is not None
assert len(loaded.heroes) == 2
Loading

Back | FazBrowse Home | New Git URL