On 06/30/2010 03:32 AM, Paul Johnston wrote: > Hi, > > I hope everyone's well here. It's been some time since I posted. Great > to see it up to 0.6, and even more progress on MS-SQL (although I'm > now unlikely to be using that). > > As always, I'm using SQLAlchemy as part of a web app. I have a set of > checkboxes, which I'm saving into an M:M relation. The app receives a > list of IDs from the client. To save these to the M:M, I need them as > database objects. So I'm doing (roughly): > > myobj.relation = [OtherTable.get(i) for i in ids] > > The problem with this is it's causing a database query for each id. > What I'd really like to do is somehow create a "placeholder" object > with just the id, that doesn't cost a database query to create. After > that, I'll trust flush() to do its magic as efficiently as possible. > > Paul > >
Here's an ugly way to do it, which injects a persistent OtherTable instance into the session without verifying it exists in the database. from sqlalchemy.orm import identity_key_from_primary_key from sqlalchemy.orm.attributes import instance_state def inject_persistent_instance(session, cls, primary_key): temp = cls() state = instance_state(temp) state.key = identity_key_from_primary_key(primary_key) return session.merge(temp) myobj.relation = [inject_persistent_instance(session, OtherTable, i) for i in ids] # You risk flush errors if the OtherTable rows did not exist in the database. session.flush() -Conor -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalch...@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.