SQLAlchemy等效于Active Record has_one_through

时间:2013-09-24 18:43:37

标签: sqlalchemy

SQLAlchemy的文档很棒,但有时来自Rails和Active Record的人有点压倒性。

鉴于此Active Record关系设置SQLAlchemy等同于通过中间表建立关系?

特别是给出了下面的基本Active Record示例,我试图了解如何在SQLAlchemy中定义一个等价关系,该关系可以允许Account SQLAlchemy模型绑定到AccountHistory模型。我不清楚我是否应该使用mapper函数,而且我觉得我在SQLAlchemy中缺少一些简单的东西。

class Supplier < ActiveRecord::Base
  has_one :account
  has_one :account_history, through: :account
end

class Account < ActiveRecord::Base
  belongs_to :supplier
  has_one :account_history
end

class AccountHistory < ActiveRecord::Base
  belongs_to :account
end

1 个答案:

答案 0 :(得分:0)

也许我误解了has_one_through的运作方式。回想起来,我认为你正在寻找这样的东西:

class Supplier(Base):
    __tablename__ = 'supplier'
    id = Column(Integer, primary_key=True)

class AccountHistory(Base):
    __tablename__ = 'account_history'
    id = Column(Integer, primary_key=True)
    account_id = Column(Integer, ForeignKey('account.id'))

class Account(Base):
    __tablename__ = 'account'
    supplier_id = Column(Integer, ForeignKey('supplier.id'))