I’m creating a program that holds a members list using camelot (which uses sqlalchemy ORM). There will be people that are married to each other which means a one to one relationship within the same table. This is a simplified version of the Person class:
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
I tried doing this:
married_to = relationship("Person", uselist=False, backref="persons")
married_to_id = Column(Integer, ForeignKey('persons.id'))
But it fails with:
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 ?
How could I join within the same table, or is this the wrong approach I’m using. And could it be done so if I join Person A with B, then Person B is automatically joined with A (as a marriege work – it both ways…)
I hope I’m making myself clear. :-/
I don’t expect that I’m answering your question, but wanted to point out that because of the bidirectional nature of marriage between two persons, you may want to consider a separate table to hold just marriage, with the primary key consisting of two
person_idreferences. You could also entertain the idea of keeping a history in this table by including ‘start’ and ‘end’ dates =)