[Python] after_insert hook - Instance is not persistent within ths Session

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I've got these two SQLModels:

    class Bar(SQLModel, table=True):
    id: int = Field(primary_key=True, default=None)
    some_field: int

    class Foo(SQLModel, table=True):
    id: int = Field(primary_key=True, default=None)
    bar_id: int = Field(foreign_key="Bar.id")
    bar: Bar = Relationship()


    I'm trying to set a hook on Foo to fire whenever a new item is added. Within that hook, I need access to the bar:

    def hook(_mapper, _connection, target):
    do_something_with(target.bar.some_field)

    sqlalchemy.event.listen(Foo, "after_insert", hook)


    However, target.bar is None. I tried refreshing the object:

    def hook(_mapper, _connection, target):
    session = sqlalchemy.orm.object_session(target)
    assert session is not None
    session.refresh(target)
    do_something_with(target.bar.some_field)


    but I got an error:


    Instance '<Foo at 0xdeadbeef>' is not persistent within this session
    ​

    How do I get a fully populated Foo when one is created?

    Continue reading...

Compartilhe esta Página