如示例所示。当插入新的KlocworkViolation时,我想将它的外键表属性更改为相关KlocworkViolation对象的正确计数。
class KlocworkViolation(db.Model):
metrics_id = Column(ForeignKey("metrics.id"))
metrics = relationship("Metrics", backref=backref("klockworkviolation", uselist=False))
class Metrics(db.Model):
...
klocwork_count = Column(SmallInteger, info={'verbose_name': 'Klocwork Violations', })
...
这是事件挂钩
@listens_for(KlocworkViolation, 'after_insert')
def count_kw(mapper, connection, target):
count = db.session.query(KlocworkViolation).filter_by(metrics_id=target.metrics_id).count()
print target.metrics # returns None
print target.metrics_id # returns None
target.metrics.klocwork_count=count
看来,此时我无法访问外键。