我正在使用Sqlalchemy,并尝试创建我认为是非常常见的3层一对多关系模型。我想从Family.parents访问该家庭的所有父母,我要从Parents.children访问该特定父母的所有孩子。因此,必须根据父级和家庭来选择Parents.children。如果我删除一个家庭,则应删除该家庭的所有父母和子女。
class Family(db.Model):
__tablename__ = 'Family'
name = db.Column(db.String, primary_key=True)
parents = db.relationship('Parent', back_populates='family', cascade='all,delete')
class Parent(db.Model):
__tablename__ = 'Parent'
name = db.Column(db.String, primary_key=True)
family_name = db.Column(db.String, db.ForeignKey('Family.name'), primary_key=True)
family = db.relationship('Family', back_populates='parents')
children = db.relationship('Child', back_populates='parent', cascade='all,delete')
class Child(db.Model):
__tablename__ = 'Child'
name = db.Column(db.String, primary_key=True)
parent_name = db.Column(db.String, db.ForeignKey('Parent.name'), primary_key=True)
family_name = db.Column(db.String, db.ForeignKey('Parent.family_name'), primary_key=True)
parent = db.relationship('Parent', back_populates='children')
但是,使用此定义,我得到一个'AmbiguousForeignKeysError'。如何正确实施?