gpt4 book ai didi

python - SQLAlchemy - 将模型子类定义为表的子集

转载 作者:太空狗 更新时间:2023-10-30 01:38:07 25 4
gpt4 key购买 nike

这里是 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 语句?

最佳答案

您正在寻找单表继承。

https://docs.sqlalchemy.org/en/13/orm/inheritance.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))

关于python - SQLAlchemy - 将模型子类定义为表的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25188696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com