On Dec 15, 2013, at 7:56 PM, Michael Bayer <[email protected]> wrote:
> > On Dec 15, 2013, at 6:01 PM, Richard Jones <[email protected]> wrote: > >> I have a model which defines (amongst other things): >> >> class Push(db.Model): >> __tablename__ = 'push' >> repository = db.Column(db.String) >> branch = db.Column(db.String, primary_key=True) >> before = db.Column(db.String, primary_key=True) >> after = db.Column(db.String, primary_key=True) >> merge_request_id = db.Column(db.Integer, >> db.ForeignKey('merge_request.iid')) >> >> class MergeRequest(db.Model): >> __tablename__ = 'merge_request' >> iid = db.Column(db.Integer, primary_key=True) >> repository = db.Column(db.String) >> branch = db.Column(db.String) >> pushes = db.relationship(Push, backref="merge_request") >> >> In my application I can create a MergeRequest and a Push in a transaction >> and relate them through merge_request_id but before the objects are >> committed, when I try to access "push.merge_request" the attribute is None >> but if I manually load the object I get it through "merge_request = >> MergeRequest.query.get(push.merge_request_id)”. > > so the general idea of this is described here: > http://docs.sqlalchemy.org/en/rel_0_9/faq.html#i-set-the-foo-id-attribute-on-my-instance-to-7-but-the-foo-attribute-is-still-none-shouldn-t-it-have-loaded-foo-with-id-7 > . At the end of that FAQ entry is a link to a recipe currently on the wiki > (http://www.sqlalchemy.org/trac/wiki/UsageRecipes/ExpireRelationshipOnFKChange) > which will eventually move into examples/, such that you can, if you prefer, > stay with your approach of FK manipulation and use events to incur the load > on the object side. oh and an additional note which probably should be noted in the FAQ entry - if your MergeRequest hasn’t been subject yet to an INSERT, then again the many-to-one attribute can’t be loaded until the object is flushed - since there is no actual row for this MergeRequest yet, the “merge_request_id” value doesn’t exist in the database either. However, there is a technique we added for some users who really want the many-to-one to load before the flush, which is to set it up as “load_on_pending”, this flag can be specified on the relationship(), see load_on_pending at http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html?highlight=relationship#sqlalchemy.orm.relationship. There’s also a note there about the enable_relationship_loading() method which is another method that isn’t really part of the canonical set of techniques.
signature.asc
Description: Message signed with OpenPGP using GPGMail
