[英]Many-to-many relationship on same table with association object
相關(對於無關聯對象用例): SQLAlchemy單表上的多對多關系
建立多對多關系很容易。 如上面的問題所述,在同一個表上建立多對多關系幾乎一樣容易。
與關聯對象建立多對多關系也很容易。
我似乎無法找到的是將關聯對象和多對多關系組合在一起的正確方法,左右兩側是同一個表。
所以,從簡單,天真,明顯錯誤的版本開始,我花了很長時間試圖按摩到正確的版本:
t_groups = Table('groups', metadata,
Column('id', Integer, primary_key=True),
)
t_group_groups = Table('group_groups', metadata,
Column('parent_group_id', Integer, ForeignKey('groups.id'), primary_key=True, nullable=False),
Column('child_group_id', Integer, ForeignKey('groups.id'), primary_key=True, nullable=False),
Column('expires', DateTime),
)
mapper(Group_To_Group, t_group_groups, properties={
'parent_group':relationship(Group),
'child_group':relationship(Group),
})
映射這種關系的正確方法是什么?
我猜你得到的錯誤就像Could not determine join condition between parent/child tables...
在這種情況下,將Group_To_Group
的映射器更改為以下內容:
mapper(Group_To_Group, t_group_groups, properties={
'parent_group':relationship(Group,
primaryjoin=(t_group_groups.c.parent_group_id==t_groups.c.id),),
'child_group':relationship(Group,
primaryjoin=(t_group_groups.c.child_group_id==t_groups.c.id),),
})
您也可以添加backref
以便也可以從Group
對象中導航關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.