简体   繁体   中英

Populating related table in SqlAlchemy ORM

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM