The solution is to specify the foreign_keys argument for all relationship s:
class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) group_id = Column(Integer, ForeignKey('groups.id')) admin_group_id = Column(Integer, ForeignKey('groups.id')) class Group(Base): __tablename__ = 'groups' id = Column(Integer, primary_key=True) members = relationship('User', backref='group', foreign_keys=[User.group_id]) admin = relationship('User', backref='admin_group', uselist=False, foreign_keys=[User.admin_group_id])
Perhaps consider the administrator’s attitude in the other direction to implement “a group has many members and one administrator”:
class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) group_id = Column(Integer, ForeignKey('groups.id')) group = relationship('Group', foreign_keys=[group_id], back_populates='members') class Group(Base): __tablename__ = 'groups' id = Column(Integer, primary_key=True) members = relationship('User', foreign_keys=[User.group_id], back_populates='group') admin_user_id = Column(Integer, ForeignKey('users.id')) admin = relationship('User', foreign_keys=[admin_user_id], post_update=True)
Check out post_update in the documentation . This is necessary when the two models are interdependent, referring to each other.
source share