如何更改表行的属性,这是SQLAlchemy中事件'after_insert'保存的表的外键

时间:2014-10-28 16:58:04

标签: events sqlalchemy foreign-keys

如示例所示。当插入新的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

看来,此时我无法访问外键。

0 个答案:

没有答案