SQLAlchemy: shallow copy avoiding lazy loading

I am trying to automatically create a shallow copy of an SA-mapped object. At the moment, my function is simple:

newobj = src.__class__()
for prop in class_mapper(src.__class__).iterate_properties:
    setattr(newobj, prop.key, getattr(src, prop.key))

but I have problems with lazy relationships ... Obviously, getattr starts lazy loading, but since I don’t need their values ​​right away, I would just copy the “it must be lazy loaded” state attribute ... Is this possible?

Edit: I need this for a data logging system. That is, whenever someone updates a permanent object, I need to create a new record, and then mark the old one as such.
To do this, I create a shallow copy of the object (so SQLA issues an INSERT instead of UPDATE) and works from there. The system works very well (it has been used for several months), but now I would like to improve it so that it does not need all the relationships to load first.

+5
source share
1 answer

, isinstance(prop, sqlalchemy.orm.ColumnProperty). , ( ), , . , . " " isinstance(prop, RelationProperty) and prop.secondary. :

from sqlalchemy.orm import object_mapper, ColumnProperty, RelationProperty

newobj = type(src)()
for prop in object_mapper(src).iterate_properties:
    if (isinstance(prop, ColumnProperty) or
        isinstance(prop, RelationProperty) and prop.secondary):
    setattr(newobj, prop.key, getattr(src, prop.key))

, SQLAlchemy , , , ( ) , , , , ( ).

+6
source

All Articles