SQLAlchemy - 映射器配置与声明式基础

2 投票
1 回答
2486 浏览
提问于 2025-04-15 11:16

我正在写一个多媒体档案数据库的后台,想要使用连接表继承的方式。我用的是Python和SQLAlchemy的声明式扩展。存放媒体记录的表结构如下:

_Base = declarative_base()

class Record(_Base):
    __tablename__ = 'records'

    item_id = Column(String(M_ITEM_ID), ForeignKey('items.id'))
    storage_id = Column(String(M_STORAGE_ID), ForeignKey('storages.id'))
    id = Column(String(M_RECORD_ID), primary_key=True)
    uri = Column(String(M_RECORD_URI))
    type = Column(String(M_RECORD_TYPE))
    name = Column(String(M_RECORD_NAME))

这里的 type 列是一个区分符。现在我想从 Record 类定义一个子类 AudioRecord,但我不知道如何用声明式语法设置多态映射器。我在找一个和以下代码(来自SQLAlchemy文档)等效的写法:

mapper(Record, records, polymorphic_on=records.c.type, polymorphic_identity='record')
mapper(AudioRecord, audiorecords, inherits=Record, polymorphic_identity='audio_record')

我该如何将 polymorphic_onpolymorphic_identityinherits 这些关键字传递给声明式扩展创建的映射器呢?

谢谢你,
Jan

1 个回答

撰写回答