关系方块中的多态性



我有一个与单表继承有关系的 SqlAchemy 模型,如下所示:

@Schema(nested=['sensor', 'mad_version', 'serial_interface'], fields=('sensor',))
class Mad(sql.Model):
#columns...
serial_interface = relationship(SerialInterface, uselist=False, cascade="all, delete-orphan")
@Schema(nested=['serial_protocol'])
class SerialInterface(sql.Model, InheritanceModel):
id = sql.Column(types.Integer, primary_key=True)
transmission_rate = sql.Column(types.Integer)
mad_id = sql.Column(types.Integer, sql.ForeignKey('mad.id'))
serial_protocol = sql.relationship(SerialProtocol, uselist=False, cascade="all, delete-orphan")
class RS485(SerialInterface):
parity = sql.Column(EnumSmart(Parity))
data_bits = sql.Column(types.Integer)
stop_bits = sql.Column(types.Integer)
polymorphic_identity = SerialTypes.RS485.name
class Ethernet(SerialInterface):
#Others Columns

我的疑问是如何查询疯狂模型并返回 Child 属性?因为现在它只返回 SerialInterface 如果他自己的属性(没有子属性(。我在文档中看到我可以在 polimorfism 中使用with_polymorphic,但是这种 polimorfism 在关系内部,有没有办法覆盖关系查询?

我发现该解决方案在__mapper_args__中添加了'with_polymorphic': '*',如下所示:

@declared_attr
def __mapper_args__(cls):
return {
'polymorphic_identity': cls.__name__,
'polymorphic_on': cls.type,
'with_polymorphic': '*'
}

最新更新