0

The problem I am having is When I create my SQLAlchemy model without loading the relationships and immediately commit after, no action is taken as expected (Great). But when I create it with the relationships loaded (based on some ids passed in) and then immediately commit, it tries to insert the data into the database.

Example:

Hero(id=event.stream_id,
      name=event.event_payload["name"])
db.commit()

^ In the above nothing happens, which makes sense because I haven't added the model to the session or tried to insert into a table.

Hero(id=event.stream_id,
      name=event.get("name"),
      teams=[teams.get(p) for p in event.get("teams")])
db.commit()

^ This fails with a duplicate key exception as for some reason it tries to now insert the model into the DB. Is this expected behaviour? Can it be turned off?

Note:teams.get returns a list of Team()

Models for reference:

class HeroTeamLink(SQLModel, table=True):
    __tablename__ = "hero_cr_person"

    hero_id: Optional[str] = Field(
        default=None, foreign_key="hero.id", primary_key=True
    )
    team_id: Optional[str] = Field(
        default=None, foreign_key="team.id", primary_key=True
    )

class Hero(SQLModel, table=True):
    __tablename__ = "hero"
    id: str
    name: str
    teams: List["Team"] = Relationship(
        back_populates="heroes", link_model=HeroTeamLink
    )
class Team(SQLModel, table=True):
    __tablename__ = "team"
    team_name: str
    heroes: List[Hero] = Relationship(
        back_populates="teams", link_model=HeroTeamLink
    )
  • I had to `session.expunge_all` in order to clear it, it seems instantiating relationship objects primes the parent for insert. –  Sep 29 '22 at 09:16

0 Answers0