1. 程式人生 > >flask_sqlalchemy 建立多對一關係,評論與回覆構成自引用

flask_sqlalchemy 建立多對一關係,評論與回覆構成自引用

帖子與回覆使用同一張表構成了自引用,建立多對一關係。

示例:

class Comment(db.Model):
    __tablename__ = 'comment'

    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String(128), comment="內容")
    reply_id = db.Column(db.Integer, db.ForeignKey('comment.id'), comment="回覆對應的評論id")
    replies = db.relationship("Comment", back_populates="comment")
    comment = db.relationship('Comment', back_populates='replies', remote_side=[id])
    
    def __repr__(self):
        return u'<Comment id={0}, text={1}>'.format(self.id, self.text)

執行示例:

>> comment1 = Comment()
>> reply1 = Comment()
>> reply2 = Comment()
>> comment1.text = "內容1"
>> db.session.flush()
>> reply1.text = "內容回覆1"
>> reply2.text = "內容回覆2"
>> reply1.reply_id = comment1.id
>> reply2.reply_id = comment1.id
>> db.session.commit()
>> comment1.replies  # 檢視評論對應的回覆
 [<Comment id=2, text=內容回覆1>, <Comment id=3, text=內容回覆22>]
>> reply1.comment # 查看回復對應的評論
 <Comment id=1, text=內容1>

注意: remote_side 欄位用於建立多對一的關係,如果不加這個欄位報下面這個錯

sqlalchemy.exc.ArgumentError: User.users and back-reference User.leader are both of the same direction symbol('ONETOMANY'). 
Did you mean to set remote_side on the many-to-one side ?

參考文件:
https://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.relationship.params.remote_side