当前位置: 首页 > 工具软件 > SIDE > 使用案例 >

SQLAlchemy之relationship之remote_side

许亦
2023-12-01

需要给每个user添加一个leader, 于是在user表里添加leader, 而leader也是一个user, 于是构成了自引用。

1
2
3
4
5
6
7
8
9
10
11
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(Integer, primary_key=True)
    name = db.Column(String(10))
    addresses = relationship("Address", back_populates="user")
    leader_id = db.Column(Integer, ForeignKey('users.id'))
    users = relationship("User", back_populates="leader")
    leader = relationship("User", back_populates="users", remote_side=[id])

    def __repr__(self):
        return u'<user id={0}, name={1}>'.format(self.id, self.name).encode('utf-8')

 

提示如下错误,

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

最后参考StackOverFlow上One to one self relationship in SQLAlchemySQLAlchemy One-to-Many relationship on single table inheritance - declarative
添加remote_side解决问题.

 类似资料: