如何在修改子表时更新父时间戳?
我想使用父表时间戳来检查我的其他客户端是否应更新这些表的本地版本。
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)