SQLAlchemy新手在这里。
我试图定义一个表示表数据子集的模型子类。具体来说,我希望子类映射给定ID的最新行。
例如,假设我有以下模型:
class AddressHistory(Base):
__table__ = 'address_table'
date = Column(Date, index=True, nullable=False)
id = Column(BigInteger, primary_key=True)
street = Column(String(2000))
city = Column(String(2000))
state = Column(String(2000))
zip = Column(Integer)
我想要做的是定义此模型的子类,它代表给定id的最新地址记录:
class MostRecentAddress(Address):
“””
Represents a row in AddressHistory with the most recent date for a given id.
”””
我可以传递给mapper_args
某种子查询吗?或者有没有办法将表定义为select语句?
答案 0 :(得分:0)
您正在寻找单表继承。
http://docs.sqlalchemy.org/en/rel_0_8/orm/extensions/declarative.html#single-table-inheritance
您的代码示例几乎完全是如何执行此操作的。您只需添加映射器。
class Person(Base):
__tablename__ = 'people'
id = Column(Integer, primary_key=True)
discriminator = Column('type', String(50))
__mapper_args__ = {'polymorphic_on': discriminator}
class Engineer(Person):
__mapper_args__ = {'polymorphic_identity': 'engineer'}
primary_language = Column(String(50))