Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Fix instance of related object added to session on validation #1052

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

mskrip
Copy link

@mskrip mskrip commented Aug 7, 2024

Previously, when validating instance when a session was open and the model instance had a related object a new instance of this related object was created and added to the session.

I encountered similar issue described in #897 and narrowed it down to this replicatable issue:

from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select


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")


if __name__ == "__main__":
    engine = create_engine(
        "postgresql+psycopg://<user>:<password>@localhost:5432/sqlmodel-test",
    )
    # SQLModel.metadata.create_all(engine)

    with Session(engine) as session:
        hero = session.exec(select(Hero)).one()
        print(f"{session.dirty=}")  # prints `session.dirty=IdentitySet([])`
        Hero.model_validate(hero, session=session)
        print(f"{session.dirty=}")  # prints `session.dirty=IdentitySet([Team(id=1, name='Team 1')])`

@mskrip mskrip force-pushed the main branch 2 times, most recently from 72fbec6 to 23aff38 Compare August 7, 2024 12:47
@mskrip mskrip changed the title Fix instance of related object added to session on validation 🐛 Fix instance of related object added to session on validation Aug 7, 2024
Previously, when validating instance when a session was open and the
model instance had a related object a new instance of this related
object was created and added to the session.
@alejsdev alejsdev added the bug Something isn't working label Sep 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants