SQLAlchemy ORM before-insert hook

时间:2012-12-12 00:12:08

标签: orm sqlalchemy

我正在试图弄清楚如何在从ORM插入行之前编写一个钩子来查询数据库。我希望能达到类似的目的:

class Table(Base):
    id = Column(Integer, primary_key=True)
    value = Column(Integer, nullable=False)

    def before_insert_hook(self, session):
        """Some arbitrary queries and code.  For example:"""
        if self.value is None:
            self.value = session.query(func.avg(Table.value))\
                    .filter(Table.value > 100).scalar()

我一直在阅读关于ORM事件的SQLAlchemy文档等等,但我无法弄清楚如何使用它们来实现这一点。

1 个答案:

答案 0 :(得分:2)

看起来你想要ORM Events

class Table(Base):
    ...

@listens_for(Table, 'before_insert')
def do_stuff(mapper, connect, target):
    # target is an instance of Table
    target.value = ...