Ellochka Cannibal
Ellochka Cannibal

Reputation: 1790

How to bind event on create of object in SqlAlchemy?

I have two tables A and B. I need to create a row in table B (with ForeignKey reference), after I create a new row in table A.

For example:

class A(db.Model):
    __tablename__ = 'a'

    id = Column(BigInteger, primary_key=True)
    ...

class B(db.Model):
    __tablename__ = 'b'

    id = Column(BigInteger, primary_key=True)
    a_id = Column(BigInteger, ForeignKey('a.id'), nullable=False, index=True)
    ...

What is the best solution for this case in SA?

I heard about events, but can't understand how to use them the best way in this case.

Upvotes: 0

Views: 3725

Answers (1)

Paweł Pogorzelski
Paweł Pogorzelski

Reputation: 651

A sample event :

def update_slug(mapper, connection, target):
    target.slug = slugify(target.name)
    if target.name_en:
        target.slug_en = slugify(target.name_en)

event.listen(Post, 'before_insert', update_slug_with_date)
event.listen(Post, 'before_update', update_slug_with_date)

You just define a function. You need to mark it as an event (last two lines), just in your case it will be 'after_insert' and probably 'after update' on the A model. In the function you can do something like this :

b = B()
b.a = target
b.save()

target here is the instance on which event is being raised.

EDIT FROM THE COMMENT TO MARK THE RIGHT ANSWER : According to docs you can't do it in event but in SessionEvents.after_flush . You should check out the docs : http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.MapperEvents.after_insert

Upvotes: 3

Related Questions