[email protected] wrote:
> On 2015-03-07 03:17 <[email protected]> wrote: >> Is there a in-build-function to duplicate the instance of a data >> object (except the primary key)? > > Isn't there a way for this? > > Does the sqla-devs reading this list? there’s no particular “SQLAlchemy way” to do this, there’s many ways to copy an object in Python in general as well as in SQLAlchemy, it depends on your needs. If the object has lots of attributes that aren’t mapped, then clearly that's outside the realm of SQLAlchemy. If you want to build something based on inspection of attributes that are mapped, you can build something using the inspection system where you go through properties like mapper.attrs (docs are down at the moment): from sqlalchemy import inspect mapper = inspect(MyClass) new_obj = MyClass() for attr in mapper.attrs: setattr(new_obj, attr.key, getattr(old_obj, attr.key)) that’s obviously not a very slick approach but mapper.attrs, mapper.column_attrs, etc. give you access to every attribute that the mapper knows about. For me I usually keep things extremely simple and just build a copy method: class MyClass(Base): def copy(self): return MyClass( a = self.a, b = self.b, # ... ) That’s how I’d normally do this, but of course nobody likes that system. The copy method has the advantage in that it can easily accommodate your special use cases without trying to make it guess everything. There’s also ways to do it with copy.copy() though some special steps are needed at the moment to give the new object an independent state, probably hold off on that method until we add some APIs to support that use case. Docs are down for a linode maintenance window but will be up within an hour or two. > -- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected]. > To post to this group, send email to [email protected]. > Visit this group at http://groups.google.com/group/sqlalchemy. > For more options, visit https://groups.google.com/d/optout. -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/sqlalchemy. For more options, visit https://groups.google.com/d/optout.
