Skip to main content
 首页 » 编程设计

python之SQLAlchemy之映射器配置和声明性基础

2025年05月04日9zengkefu

我正在编写一个多媒体存档数据库后端,我想使用连接表继承。我将 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_on、polymorphic_identity 和 inherits 关键字传递给声明式扩展创建的映射器?

谢谢 简

请您参考如下方法: