一对多关系sqlalchemy id's

时间:2016-12-27 00:48:27

标签: python sqlalchemy

关于this教程,对于一对多关系,我有这个简单的代码:

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,但有没有办法让孩子们获得父母的身份?

1 个答案:

答案 0 :(得分:0)

父接受子女作为列表,所以:

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