Automatic property update in sqlalchemy

I have a sqlalchemy model that is configured as follows:

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),
            )

I would like for an upgrade entrythat cached_entrygets re-generated to cached_entrybe a collapsible version entry. Basically, I cache the syntax markup output so I don't have to do this every time I record. I used t @hybrid_method, but didn't seem to work, since it is not stored at all in the database. I got his work on Google AppEngine , but I can't figure out how to do the same using SQLAlchemy.

, , , -.

+5
1

@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 - , , () .

, "on-set" @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
+6

All Articles