On Nov 18, 2011, at 6:56 AM, Alex Grönholm wrote: > My use case is the following: each SalesItem requires a calcPriceList and a > salesPriceList (of type PriceList) attached to it. > For that, SalesItem has two fields: > calcpricelist_id = Column(BigInteger, ForeignKey(PriceList.id), > nullable=False) > salespricelist_id = Column(BigInteger, ForeignKey(PriceList.id), > nullable=False) > It also has two relationships: > calcPriceList = relationship(PriceList, primaryjoin=calcpricelist_id == > PriceList.id, cascade='save-update,delete') > salesPriceList = relationship(PriceList, primaryjoin=salespricelist_id == > PriceList.id, cascade='save-update') > > Now I have a problem -- I want to create a new SalesItem. I want to minimize > the hassle so I set up a before_insert mapper listener (and verified it's > being called) that attaches transient PriceList instances to said > relationships.
The docs for before_insert() http://www.sqlalchemy.org/docs/orm/events.html#sqlalchemy.orm.events.MapperEvents.before_insert are pretty explicit that you can't do any kind of Session.add() or relationship-oriented operations there. A future release will probably raise an error when such operations occur at an incompatible point, since this is still a common mistake. Particularly in the case of "I want an X object whenever I create a Y", the simplest and most self-documenting practice is just to augment the __init__() method of Y to also produce its X object - no ORM-level event is needed here as this is not really a "hook" into the ORM, just one into your object model. If you do need an event approach here, the event most commonly used for modification of the flush plan on flush is the before_flush event: http://www.sqlalchemy.org/docs/orm/events.html#sqlalchemy.orm.events.SessionEvents.before_flush -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.