Search code examples
pythonpyramid

DetachedInstanceError: Instance <TCustomer at 0x428ddf0> is not bound to a Session


I have looked at previous examples of people having similar problems however I can't seem to figure out why mine won't work since I'm using the same session.

This is my block of code that simply queries the db to see if a customer exists, then use that customer in another insert. But as soon as i hit the line transaction.commit() it throws the DetachedInstanceError. Could this be from an earlier transaction.commit() in another method?

@view_config(route_name='create_location', renderer='templates/main.html')
def create_location(request):

    #get the json data from the ajax call
    data = request.json_body

    session = DBSession

    locationName = data["location"]
    custID = data["custID"]

    Customer = session.query(TCustomer).filter(TCustomer.ixCustomer==custID).one()

    #create customer
    Location = TLocation(sDescription=locationName, ixCustomer=Customer)
    session.add(Location)
    session.flush()
    transaction.commit()

    return Response('ok')

this is my DBSession:

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

Solution

  • Here is the solution:

    DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension(keep_session=True)))
    

    had to add the keep_session=True

    Then instead of doing session = DBSession() all I had to do was just use DBSession for my queries and session work