onupdateやeventなど

更新時刻を設定したい場合などデフォルトで提供されている、onupdateオプションを使う。

import sqlahelper
import sqlalchemy as sa
import sqlalchemy.orm as orm
from datetime import datetime

Base = sqlahelper.get_base()
DBSession = sqlahelper.get_session()

class Point(Base):
    __tablename__ = "point"
    id = sa.Column(sa.Integer, primary_key=True)
    x = sa.Column(sa.Float())
    y = sa.Column(sa.Float())
    created_at = sa.Column(sa.DateTime, default=datetime.now)
    updated_at = sa.Column(sa.DateTime, default=datetime.now, onupdate=datetime.now)

engine = sa.create_engine("sqlite://")
sqlahelper.add_engine(engine)
Base.metadata.create_all()

DBSession.add(Point(x=10, y=20))
import transaction
transaction.commit()

import time
pt =  DBSession.query(Point).first()
print pt.created_at, pt.updated_at

time.sleep(3)
pt.x = 20
DBSession.add(pt)
pt =  DBSession.query(Point).first()

print pt.created_at, pt.updated_at
import transaction
transaction.commit()

pt =  DBSession.query(Point).first()
print pt.created_at, pt.updated_at

# 2012-03-16 00:24:55.402247 2012-03-16 00:24:55.402279
# 2012-03-16 00:24:55.402247 2012-03-16 00:24:58.421079
# 2012-03-16 00:24:55.402247 2012-03-16 00:24:58.421079

あとで書く

他の時点での値の変更などがしたい場合にはeventを利用する。
MapperExtensionはオワコン。MapperEvents使う

def message_function(mapper, connection, target):
    print ("Instance %s being inserted" % target)

# attach to all mappers
sa.event.listen(Point, 'before_insert', message_function)
DBSession.add(Point(x=20, y=1))
transaction.commit()

#
# Instance <__main__.Point object at 0x192add0> being inserted