2010-04-12 31 views
5

我對SQLAlchemy甚至數據庫編程頗爲陌生,也許我的問題太簡單了。 現在我有兩個班/表:聲明式風格的入門者問題SQLAlchemy關係()

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. 

在Computer類中有兩個外鍵,所以relation()調用無法確定應該使用哪一個。我想我必須使用額外的參數來指定它,對吧? 和howto?由於

回答

10

正確的語法應爲:

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

附:下次請通過發佈回溯來指定「無法運行」的含義。

更新:在更新的問題回溯說,正是你需要的:指定primaryjoin條件:

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

感謝您的諮詢。錯字已被修復,追溯已追加。 – jfding 2010-04-13 10:56:38

+0

謝謝,問題解決了。 – jfding 2010-04-15 14:52:10