1

我已经在现有数据库上完成了大量的 python/Elixir 接口。我现在正在考虑放弃 Elixir 并将所有内容转移到纯 SQLAlchemy 中,很可能想要使用声明性方法。

我什至不知道从哪里开始这种特殊的继承关系。我不认为 sqlalchemy 以这种方式(或“神奇地”)执行继承,而且我有点困惑 sqlalchemy 中的相同情况:

这是一个多态多表连接,每个类都映射到自己的数据库表。完成后,另一个类(此处未包括)将有一个带有“Comp”的 OneToMany。Comp 子类有一个主键,它是 Comp.id 的外键。

class Comp(Entity):
    using_options(inheritance='multi')
    parent = ManyToOne('Assembly', onupdate='cascade', ondelete='set null')
    quantity = Field(Numeric(4), default=1)

    def __repr__(self):
        return "<Comp>"

## If not familiar with Elixir, each of the following "refid" point to a different
## table depending on its class. This is the primary need for polymorphism.    

class CompAssm(Comp):
    using_options(inheritance='multi')
    refid = ManyToOne('Assembly', onupdate='cascade', ondelete='set null')

    def __repr__(self):
        return "<CompAssm>"

class CompItem(Comp):
    using_options(inheritance='multi')
    refid = ManyToOne('Item', onupdate='cascade')

    def __repr__(self):
        return "<CompItem>"

class CompLabor(Comp):
    using_options(inheritance='multi')
    refid = ManyToOne('Labor', onupdate='cascade')

    def __repr__(self):
        return "<CompLabor>"
4

1 回答 1

0

我认为这是大方向,但可能仍需要调整。

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Assembly(Base):
    __tablename__ = 'assembly'
    assm_id = Column(Integer, primary_key=True)
    children = relationship('Comp')    

    ### other assembly stuff

class Comp(Base):
    __tablename__ = 'components'
    id = Column(Integer, primary_key=True)
    comp_type = Column('type', String(50))
    __mapper_args__ = {'polymorphic_on': comp_type}
    parent = Column(Integer, ForeignKey('assembly.assm_id'))
    quantity = Column(Integer)

class CompAssm(Comp):
    __tablename__ = 'compassm'
    __mapper_args__ = {'polymorphic_identity': 'compassm'}
    id = Column(Integer, ForeignKey('components.id'), primary_key=True)
    refid = Column(Integer, ForeignKey('assembly.assm_id'))

 class CompItem(Comp):
    __tablename__ = 'compitem'
    __mapper_args__ = {'polymorphic_identity': 'compitem'}
    id = Column(Integer, ForeignKey('components.id'), primary_key=True)
    refid = Column(Integer, ForeignKey('items.id'))

class CompLabor(Comp):
    __tablename__ = 'complabor'
    __mapper_args__ = {'polymorphic_identity': 'complabor'}
    id = Column(Integer, ForeignKey('components.id'), primary_key=True)
    refid = Column(Integer, ForeignKey('labors.id'))
于 2013-04-22T19:32:49.813 回答