Nikolay Shevchenko
Nikolay Shevchenko

Reputation: 51

sqlalchemy.event.listen not found event "after_create"

I have a table Test and want`s to add a constraint for column '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]')")
)

this code returns error:

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

How can I solve it?

Upvotes: 5

Views: 6544

Answers (1)

SuperShoot
SuperShoot

Reputation: 10872

after_create is a core event, not an ORM event, so it doesn't accept an ORM class as it's target arg. From the docs:

target – the MetaData or Table object which is the target of the event.

It needs the table that your ORM model represents, not the model. An example solution might be:

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]')"
    )

Upvotes: 9

Related Questions