我正在创建一个使用 camelot(使用 sqlalchemy ORM)保存成员列表的程序。会有人结婚,这意味着同一张 table 内的一对一关系。这是 Person 类的简化版本:
class Person( Entity ):
id = Column(Integer, primary_key=True)
firstname = Column( Unicode(30), nullable = False )
lastname = Column( Unicode(30), nullable = False )
member_no = Column( Integer )
marital_status = Column( Unicode(15) )
marriage_date = Column( Date() )
married_to = ... # Should be one to one with self
我试过这样做:
married_to = relationship("Person", uselist=False, backref="persons")
married_to_id = Column(Integer, ForeignKey('persons.id'))
但它失败了:
InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Original exception was: Person.married_to and back-reference Person.persons are both of the same direction . Did you mean to set remote_side on the many-to-one side ?
我如何在同一个表中加入,或者这是我使用的错误方法。如果我将 A 和 B 结合起来,那么 B 会自动与 A 结合吗(作为婚姻工作 - 两种方式......)
我希望我说清楚了。 :-/
请您参考如下方法:
您需要邻接列表关系。这是 documentation .
The relationship() configuration here works in the same way as a “normal” one-to-many relationship, with the exception that the “direction”, i.e. whether the relationship is one-to-many or many-to-one, is assumed by default to be one-to-many. To establish the relationship as many-to-one, an extra directive is added known as remote_side, which is a Column or collection of Column objects that indicate those which should be considered to be “remote
也许试试:
married_to = relationship("Person", remote_side=[id])
