Reputation: 4298
So I have two table in a one-to-many relationship. When I make a new row of Table1
, I want to populate Table2
with the related rows. However, this population actually involves computing the Table2
rows, using data in other related tables.
What's a good way to do that using the ORM layer? That is, assuming that that the Table1
mappings are created through the ORM, where/how should I call the code to populate Table2
?
I thought about using the after_insert
hook, but i want to have a session to pass to the population method.
Thanks.
Upvotes: 1
Views: 836
Reputation: 4298
After asking around in #sqlalchemy IRC, it was pointed out that this could be done using ORM-level relationships in an before_flush
event listener.
It was explained that when you add a mapping through a relationship, the foreign key is automatically filled on flush, and the appropriate insert statement generated by the ORM.
Upvotes: 1
Reputation: 2147
You can use the before_flush
or after_flush
hook, it provides a session
. You then check session.new
objects for newly created models (tip: use isinstance(object, ModelClass)
) and do your work here.
In fact, SQLAlchemy recommends before_flush
for general on flush changes.
Mapper-level flush events only allow very limited operations, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given Connection. Please read fully the notes at Mapper-level Events for guidelines on using these methods; generally, the SessionEvents.before_flush() method should be preferred for general on-flush changes.
Upvotes: 1