2010-04-12 4 views
5

SQLAlchemy 또는 데이터베이스 프로그래밍에 새로운 것이므로 어쩌면 내 질문이 너무 간단 할 것입니다. 지금은 두 개의 클래스/테이블이 :선언 스타일의 초급 질문 SQLAlchemy relation()

class User(Base): 
    __tablename__ = 'users' 
    id = Column(Integer, primary_key=True) 
    name = Column(String(40)) 
    ... 

class Computer(Base): 
    __tablename__ = 'comps' 
    id = Column(Integer, primary_key=True) 
    buyer_id = Column(None, ForeignKey('users.id')) 
    user_id = Column(None, ForeignKey('users.id')) 
    buyer = relation(User, backref=backref('buys', order_by=id)) 
    user = relation(User, backref=backref('usings', order_by=id)) 

물론, 그것을 실행할 수 없습니다. 이것은 백 트레이스입니다 :

File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/state.py", line 71, in initialize_instance 
    fn(self, instance, args, kwargs) 
    File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/mapper.py", line 1829, in _event_on_init 
    instrumenting_mapper.compile() 
    File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/mapper.py", line 687, in compile 
    mapper._post_configure_properties() 
    File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/mapper.py", line 716, in _post_configure_properties 
    prop.init() 
    File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/interfaces.py", line 408, in init 
    self.do_init() 
    File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/properties.py", line 716, in do_init 
    self._determine_joins() 
    File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/properties.py", line 806, in _determine_joins 
    "many-to-many relation, 'secondaryjoin' is needed as well." % (self)) 
sqlalchemy.exc.ArgumentError: Could not determine join condition between parent/child tables on relation Package.maintainer. Specify a 'primaryjoin' expression. If this is a many-to-many relation, 'secondaryjoin' is needed as well. 

컴퓨터 클래스에는 2 개의 외래 키가 있으므로 relation() 호출은 어느 것을 사용해야하는지 결정할 수 없습니다. 그것을 지정하기 위해 추가 인수를 사용해야한다고 생각합니다. 맞습니까? 그리고 howto? 감사합니다

답변

10

올바른 구문은 다음과 같습니다

buyer = relation(User, backref=backref('buys', order_by=id)) 
user = relation(User, backref=backref('usings', order_by=id)) 

P.S. 다음에 트레이스 백을 게시하여 "실행할 수 없음"이 무엇을 의미하는지 지정하십시오.

업데이트 : 업데이트 된 문제의 역 추적 당신이 필요로하는 무엇을 정확하게 말한다 : 당신의 조언을

buyer = relation(User, primaryjoin=(buyer_id==User.id), 
       backref=backref('buys', order_by=id)) 
user = relation(User, primaryjoin=(user_id==User.id), 
       backref=backref('usings', order_by=id)) 
+0

감사 : primaryjoin 조건을 지정합니다. 오타가 수정되어 백 트레이스가 추가되었습니다. – jfding

+0

감사합니다. 문제가 해결되었습니다. – jfding