[Python] SQLModel session handling when my read and updates are in seperate parts of the code...

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have a script that needs to query some data, process it, and then update some columns in the row I read.

    My code looks like this:

    def query_data(param1):
    with Session(engine) as session:
    statement = select(
    FreddyInsightsInfo).where(SampleModel.col1 == param1,
    FreddyInsightsInfo.col2.is_(None)
    )
    data_list = session.scalars(statement).all()
    return data_list


    def save_object(data, param3):
    with Session(engine) as session:
    data.col3 = param3
    session.add(data)
    session.commit()


    data_list = query_data(param1)
    for data in data_list:
    # some processing here
    save_object(data, param3)


    When I do this, I cam getting an error that says

    DetachedInstanceError: Instance <...> is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: https://sqlalche.me/e/20/bhk3)


    I am not sure how to fix this. I have tried expunging the objects after querying it in query_data, but it didn't fix the issue

    Continue reading...

Compartilhe esta Página