flask_sqlalchemy 建立多对一关系,评论与回复构成自引用

版权声明: https://blog.csdn.net/u011361138/article/details/84662007

帖子与回复使用同一张表构成了自引用,建立多对一关系。

示例:

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

猜你喜欢

转载自blog.csdn.net/u011361138/article/details/84662007