我有一个像这样设置的 sqlalchemy 模型:
class Entry(Base):
__tablename__ = 'entries'
__table__ = Table('entries', Base.metadata,
Column('id', Integer, primary_key=True, unique=True),
Column('user_id', Integer, ForeignKey('users.id', onupdate="CASCADE", ondelete="RESTRICT")),
Column('title', String(128)),
Column('slug', String(128), index=True),
Column('url', String(256), index=True),
Column('entry', Text),
Column('cached_entry', Text),
Column('created', DateTime, server_default=text('current_timestamp')),
Column('modified', DateTime, server_onupdate=text('current_timestamp')),
Column('pubdate', DateTime),
)
我想要的是当我更新 entry
时那cached_entry
重新生成,cached_entry
是 entry
的 Markdown 解析版本.基本上我正在缓存 Markdown 解析的输出,这样我就不必在每次显示条目时都这样做。我试过使用 @hybrid_method
然而,这似乎没有用,因为它根本没有存储在数据库中。我有 got it working on Google AppEngine , 但我似乎无法弄清楚如何使用 SQLAlchemy 做同样的事情。
我真的宁愿不必向使用的类添加函数而不是模型中的名称,因为从应用程序的角度来看更难强制执行它,我不想不小心错过一些东西。
最佳答案
@hybrid_descriptor 当然使用 http://www.sqlalchemy.org/docs/orm/mapper_config.html#using-descriptors 中描述的形式来完成它.您分配给数据库映射属性,您可以将其映射到不同的名称下 - 因为您使用的是 __table__
,所以您可以使用如下形式:
class Entry(Base):
__table__ = ...
_entry = __table__.c.entry
@hybrid_property
def entry(self):
return self._entry
@entry.setter
def entry(self, value):
self._entry = value
self.cached_entry = markdown(value)
另一种方法是使用 before_insert 和 before_update 事件在刷新时填充列 - 这是一种简单的方法,但缺点是您必须等待 flush() 才能发生。
我认为“现场”的最快方法是使用@validates:
from sqlalchemy.orm import validates
class Entry(Base):
__table__ = ...
@validates('entry')
def _set_entry(self, key, value):
self.cached_entry = markdown(value)
return value
关于python - 在 sqlalchemy 中自动更新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6422248/