我正在寻找定义两个人之间关系并在 SQLAlchemy 中查询它的最佳方法。我很难理解这一点。这是我到目前为止所拥有的,但我不知道我是否应该将模型用作这样的链接表。建议?
示例character_a
= student
character_b
=teacher
或[[relationship.character_b, relationship.character_b.role] for relationship in character.relationships]
获取相关角色及其角色的列表。
class Character(db.Model):
__tablename__ = 'characters'
story_id = db.Column(db.String, db.ForeignKey('stories.id'))
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50))
gender = db.Column(db.String(6))
description = db.Column(db.Text())
relationships = db.relationship('Relationship', backref='character', lazy='dynamic')
class Relationship(db.Model):
__tablename__ = 'relationships'
character_a_id = db.Column(db.String, db.ForeignKey('characters.id'))
character_b_id = db.Column(db.String, db.ForeignKey('characters.id'))
character_a_role = db.Column(db.String(25))
character_b_role = db.Column(db.String(25))