On Jul 29, 1:43 pm, Mike Conley <mconl...@gmail.com> wrote: > I have a need to clone an instance of a mapped class and insert the new > instance in my database with only minor changes to attributes. To do this I > want to create a new instance of the class with all non-key attributes > copied from the old instance. Primary keys and foreign keys will be > populated at insert time via normal processes for any instance. > > Here is a function I wrote to clone the non-key attributes to a new > instance. Does this make sense or might I stumble into an unseen abyss > somewhere, or is there an easier way to do this? (I did not use copy.copy() > because I only want the non-key attributes copied) > None of the classes involve polymorphism which is one area I thought there > might be trouble. > All of our classes use the default declarative __init__(), so the statement > new = cls() is valid in all cases. > > def clone_instance(old): > cls = old.__class__ > tbl = cls.__table__ > new = cls() > for c in tbl.c: > if c.primary_key or c.foreign_keys: > continue > setattr(new, c.name, getattr(old,c.name)) > return new > > usage is something like this > > obj = session.query(SomeClass).get(someid) > newobj = clone_instance(obj) > newobj.someattribute = some different value > session.add(newobj) > session.commit() > > This seems to work for the simple cases I ran so far, just wondering if > there are any hidden problems or simplifications.
I'd love to find a reasonable way of cloning an instance, even with the caveat that one could only copy attributes that are no primary or foreigh key related. Still, I to make that code "work" w/newer versions of SA: def clone_instance(old): new = type(old)() m = sa_orm.object_mapper(old) for c in m.columns: if c.primary_key or c.foreign_keys: continue setattr(new, c.name, getattr(old,c.name)) return new --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---