On Feb 8, 2012, at 10:29 AM, Michael Hipp wrote: > I have an ORM object that gets loaded once during program run and never > changes. > > sess = Session() > unchanging = sess.query(Unchanging).get(1) > sess.close() # it is now detached > > I then need to tell other objects about about it, having a many-to-one > relationship to 'unchanging': > > sess1 = Session() > thing1 = Thing() > thing1.unchanging = unchanging > sess1.add(thing1) > sess1.commit() > > sess2 = Session() > thing2 = Thing() > thing2.unchanging = unchanging > sess2.add(thing2) # fails InvalidRequestError > sess2.commit() > > This doesn't work, of course, because 'unchanging' becomes attached to sess1. > > Is there some way I can keep 'unchanging' detached and use it over and over > again? Or make a copy of it before attaching it to 'thing'? Or must I load a > fresh copy every time I need to use it somewhere?
keep it detached, and when you need it to be used within the context of a Session, use unchanging = sess1.merge(unchanging, dont_load=True). This will give you a copy of it that will participate in that session like any other object. The "dont_load" thing prevents it from emitting any SQL on the merge but it's important that "unchanging" doesn't have any dirty state on it (such as a collection that changes when you say "thing.unchanging = unchanging"). -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.