我使用SQLAlchemy ORM从数据库加载/保存。但是,我希望在从数据库加载数据时调用特定的函数,如下所示:
class MyClass(Base):
id = Column(Integer, primary_key = True)
_data = relationship('Data')
def __init__(self):
self._data = []
self.max_data = None
self.min_data = None
@property
def data(self):
return self._data
@data.setter
def data(self, data):
print('gone through setter')
self.min_data = min(data)
self.max_data = max(data)
self._data = data
但是,我注意到从db保存/加载时没有调用setter和getter。有没有办法让这些定位器和吸气剂调用?
myclass = MyClass()
myclass.data = [0,1,2,3,4,5]
# gone through setter
myclass.max_data
# 5
myclass.min_data
# 0
session.add(myclass)
session.commit()
del myclass
myclass = session.query(MyClass).all()[0]
# setter is not called here
myclass.max_data
# None
myclass.min_data
# None
我希望在从db加载时调用setter,以便设置min_data
和max_data
(无需明确地将它们保存在db中)
答案 0 :(得分:2)
要在加载时附加行为,请使用load
event:
@event.listens_for(MyClass, "load")
def _set_min_max_on_load(target, context):
target.max_data = max(target._data)
target.min_data = min(target._data)
在这个特定的例子中,简单地使用hybrid_property
代替:
class MyClass(Base):
...
@hybrid_property
def max_data(self):
return max(self.data)
@max_data.expression
def max_data(cls):
return select([func.max(Data.__table__.c.some_value)]).where(Data.__table__.c.my_class_id == cls.id)