2016-12-27 97 views
0

this教程,對於一對多的關係,我有這個簡單的代碼:一對多的關係SQLAlchemy的ID的

class Parent(Base): 
    __tablename__ = 'parent' 
    id = Column(Integer, primary_key=True) 
    children = relationship("Child", back_populates="parent") 

class Child(Base): 
    __tablename__ = 'child' 
    id = Column(Integer, primary_key=True) 
    parent_id = Column(Integer, ForeignKey('parent.id')) 
    parent = relationship("Parent", back_populates="children") 

現在的問題是填充parent_id,每當我把孩子作爲一個列表,提交結果到數據庫,如下所示:

# assume I have a session 
children = Child(), Child(), Child() 
p = Parent(children=children) 
session.add(p) 
session.commit() 

如果我檢查在此時數據庫,parent_id不填充。我想這是有道理的,因爲我沒有明確定義parent_id在任何地方,但有沒有辦法讓孩子們獲得父母身份證?

回答

0

父母接受孩子的列表,以便:

children = [Child(), Child(), Child()] 
... 
p = Parent.query.first() 
for child in p.children: 
    print(child.parent_id) 
相關問題