关于声明式风格SQLAlchemy relation()的入门问题

5 投票
1 回答
4725 浏览
提问于 2025-04-15 21:30

我对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()的时候,系统不知道应该用哪一个。我想我需要用额外的参数来指定,没错吧?那该怎么做呢?谢谢!

1 个回答

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

撰写回答