[英]One-to-one self-referential relationship using an association table in SqlAlchemy
所以我在Topic
模型與此類所表示的關系之間有一個父子關系:
class ParentChildRelation(db.Model):
__tablename__ = 'parent_child_relation'
id = db.Column(db.Integer, primary_key=True)
child_topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'), nullable=False)
parent_topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'), nullable=False)
主題定義如下:
class Topic(db.Model):
__tablename__ = 'topic'
id = db.Column(db.Integer, primary_key=True)
parent = db.relationship(
'Topic',
secondary='parent_child_relation',
primaryjoin='Topic.id == ParentChildRelation.child_topic_id',
secondaryjoin='Topic.id == ParentChildRelation.parent_topic_id'
)
我現在想讓parent
成為一對一的關系(我可能會在以后更改),但是它以InstrumentedList
。 是否有一種簡單的方法來聲明parent
應該是一對一的關系,以便它直接鏈接到Topic
模型而不是InstrumentedList
?
事實證明,我以前已經找到了正確的答案,但是我一定有錯字:/。 添加uselist = False可以解決問題。
parent = db.relationship(
'Topic',
secondary='parent_child_relation',
primaryjoin='Topic.id == ParentChildRelation.child_topic_id',
secondaryjoin='Topic.id == ParentChildRelation.parent_topic_id',
uselist=False
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.