views:

232

answers:

1

I am quite new to SQLAlchemy, or even database programming, maybe my question is too simple. Now I have two class/table:

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))

Of course, it cannot run. This is the backtrace:

  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.

There's two foreign keys in class Computer, so the relation() callings cannot determine which one should be used. I think I must use extra arguments to specify it, right? And howto? Thanks

+1  A: 

The correct syntax should be:

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

P.S. Next time please specify what do you mean by "cannot run" by posting a traceback.

Update: the traceback in updated question says exactly what you need: specify primaryjoin condition:

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))
Denis Otkidach
thanks for your advice. The typo has been fixed, and backtrace has been appended.
jfding
thanks, problem resolved.
jfding