2013-02-04 2 views
1

camelot (sqlalchemy ORM을 사용)을 사용하여 회원 목록을 보유하는 프로그램을 만들고 있습니다. 서로 결혼하여 같은 테이블에서 일대일 관계를 의미하는 사람들이있을 것입니다."Join"in same table

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 

내가이 일을 시도 : 이것은 Person 클래스의 단순화 된 버전입니다

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 ?

, 또는 이것은 내가 사용하고있는 잘못된 접근법입니다. 그리고 제가 Person A와 B를 합치면 B가 자동으로 A와 합류합니다. (두 가지 모두 ...)

나는 분명히하고 싶습니다. : -/

+0

한숨과 .... 1 대 1? 왜 결혼 생활은 일 일부일처 제를 의미합니까? – paddy

+0

나는 이것을 만들 때 그것을 생각했다. 하지만 우리나라의 법에 따르면 일부 다처제는 허용되지 않습니다. 법률이 바뀌면 내 소프트웨어를 바꿀 것 같아 .-p –

답변

2

저는 여러분의 질문에 대답하고 싶지는 않지만 두 사람 사이의 결혼의 양방향 특성 때문에 결혼 생활을 유지하기 위해 별도의 테이블을 고려하고 싶을 수도 있습니다. 키는 두 개의 person_id 참조로 구성됩니다. 또한 '시작'과 '종료'날짜 =를 포함하여이 표에 기록을 유지하는 아이디어를 접할 수 있습니다. =)

3

Adjacentcy 목록 관계가 필요합니다. 다음은 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]) 
+0

나는 이것이 내가 갈 길이라고 생각한다. 그러나 아직 확실하지 ... –

1

을이 모두 동일한 테이블 내에서, 당신은 외래 키를 사용할 수없는 경우. 외래 키는 정의 상 다른 테이블의 키입니다.

저는 서로 결혼 한 사람들이 각각 id이되도록 married_to 열을 사용합니다. 그러면 쿼리가 매우 단순해질 것입니다.