0

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Pawel, Thx for the help! Could you tell me why even if I do commit inside the event listener I get the TransactionClosed error? Can I use transaction inside and rollback on exception? I can't find in documentation what types of actions can I use inside event listener (for example, session commit, sql expressions, orm actions, new transactions and etc.)
Sorry. My pointer was somewhat wrong (short term memory ;) ) : According to docs you can't do it in event but in SessionEvents.after_flush . You should check out the docs in docs.sqlalchemy.org/en/rel_0_8/orm/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.