找不到sqlalchemy.event.listen事件“ after_create”

时间:2019-03-19 09:40:08

标签: python-3.x events sqlalchemy

我有一个表Test,希望为'progress'列添加约束

class Test(Base):
__tablename__ = 'test'

id = Column('id', INTEGER, primary_key=True)
name = Column('name', VARCHAR(30))
progress = Column('progress', VARCHAR(4), server_default='0')


event.listen(
Test,
"after_create",
DDL("ALTER TABLE test ADD CONSTRAINT "
    "cst_test_progress "
    " CHECK (progress like '[0-9]')")
)

此代码返回错误:

sqlalchemy.exc.InvalidRequestError: No such event 'after_create' for target '<class '__main__.Test'>'

我该如何解决?

1 个答案:

答案 0 :(得分:0)

after_createcore事件,而不是ORM事件,因此它不接受ORM类,因为它是target arg。从文档中:

  

目标 –作为目标的MetaData或Table对象   事件。

它需要您的ORM模型代表的表,而不是模型。解决方案的示例可能是:

from sqlalchemy import event

@event.listens_for(Test.__table__, 'after_create')
def receive_after_create(target, connection, **kw):
    connection.execute(
        "ALTER TABLE test ADD CONSTRAINT "
        "cst_test_progress "
        " CHECK (progress like '[0-9]')"
    )