修改子表时如何更新父表时间戳?

时间:2016-02-05 16:51:25

标签: python sqlalchemy flask-sqlalchemy

如何在修改子表时更新父时间戳?

我想使用父表时间戳来检查我的其他客户端是否应更新这些表的本地版本。

class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    version = db.Column(db.Integer)
    timestamp = db.Column(db.DateTime,
                          default=datetime.utcnow,
                          onupdate=datetime.utcnow)
    childs = db.relationship('Children',
                             backref='parent',
                             lazy='dynamic',
                             cascade="all, delete-orphan")

class Children(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    version = db.Column(db.Integer)
    timestamp = db.Column(db.DateTime,
                          default=datetime.utcnow,
                          onupdate=datetime.utcnow)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'), nullable=False)

测试一下:

    db.create_all()
    parent = Parent(version=1)
    child = Children(version=1, parent=parent)
    db.session.add_all([parent, child])
    db.session.commit()
    print "parent timestamp: %s, child timestamp %s" % (parent.timestamp, child.timestamp)
    previous_timestamp = parent.timestamp
    parent.version = 2
    db.session.add(parent)
    db.session.commit()
    assert parent.timestamp != previous_timestamp # this works
    print "parent timestamp: %s, child timestamp %s" % (parent.timestamp, child.timestamp)
    previous_timestamp = parent.timestamp
    child.version = 2
    db.session.add(child)
    db.session.commit()
    # this fails. Parent timestamp is not updated when child is modified
    assert parent.timestamp != previous_timestamp
    print "parent timestamp: %s, child timestamp %s" % (parent.timestamp, child.timestamp)

1 个答案:

答案 0 :(得分:5)

使用SQLAlchemy events作为此question的回答。

请参阅下面一个使用内存中SQLite数据库和您的数据模型的自包含Flask示例(请注意,我已将您的Children类更改为Child以及关系{{1} } childs

浏览三个路径/ insert_child /,/ delete_child /和/ update_child /以查看父时间戳更改。

children