开发者

SQLAlchemy - difference between mapped orm.relation with backref or two orm.relation from both sides

In some project I implement user-requested mapping (at runtime) of two tables which are connected by a 1-to-n relation (one table has a ForeignKey field).

From what I get from the documentation, the usual way is to add a orm.relation to the mapped propert开发者_StackOverflowies with a mapped_collection as collection_class on the non-foreignkey table with a backref, so that in the end both table orm objects have each other mapped on an attribute (one has a collection through the collection_class of the orm.relation used on it, the other has an attribute placed on it by the backref).

I am in a situation where I sometimes do just want the ForeignKey-side to have a mapped attribute to the other table (that one, that is created by the backref), depending on what the user decides (he might just want to have that side mapped).

Now I'm wondering whether I can simply use an orm.relation on the ForeignKey table aswell, so I'd probably end up with an orm.relation on the non-foreignkey table as before with a mapped_collection but no backref, and another orm.relation on the foreignkey table replacing that automagic backref (making two orm.relations on both tables mapping each other from both sides).

Will that get me into trouble? Is the result equivalent (to just one orm.relation on the non-foreignkey table with a backref)? Is there another way how I could map just on the ForeignKey-side without having to map the dictionary on the non-ForeignKey table aswell with that backref?


I found the answer myself by now:

If you use an orm.relation from each side and no backrefs, you have to use back_populates or if you mess around at one side, it won't be properly updated in the mapping on the other side.

Therefore, an orm.relation from each side instead of an automated backref IS possible but you have to use back_populates accordingly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜