@event.listens_for(Comment, 'after_insert')
def after_insert(mapper, connection, target):
    thread_table = Thread.__table__
thread = target.thread
connection.execute(thread_table.update().where(thread_table.c.id == thread.
    id).values(word_count=sum(c.word_count for c in thread.comments)))
print('updated cached word count to', thread.word_count)
Can SQLAlchemy events be used to update a denormalized data cache?