我有一个模型,它是抽象类的多态性身份
class AbstractModel(Base):
type = Column(String())
__mapper_args__ = {"polymorphic_on": type}
class ModelA(AbstractModel):
__mapper_args__ = {"polymorphic_identity": "model_a"}
class FlaskModel(ModelA):
__mapper_args__ = {"polymorphic_identity": "model_a"}
我需要FlaskModel与ModelA具有相同的多态关系,因为FlaskModel具有在ModelA中不存在的特定于约束的约束(请求上下文,用户权限等)
但是,在创建第二个类时,SQLAlchemy会抛出有关重复的警告,这是有充分理由的,因为任何查询始终指向FlaskModel,即使它们是从ModelA查询的。
有关完成此操作的任何建议吗?将代码拆分为包然后导入不是一个选项。
答案 0 :(得分:0)
I ended up using this route, which worked well and allowed me to create flask specific functions.
class AbstractModel(Base):
type = Column(String())
__mapper_args__ = {"polymorphic_on": type}
class ModelA(AbstractModel):
__mapper_args__ = {"polymorphic_identity": "model_a"}
class FlaskModel(ModelA):
pass
##Event listeners are requireed for the inherited polymorphic relationships
##If additional work needs to be done with different aspect, including after_delete and after_update
##They can als be added here
@event.listens_for(FlaskModel, 'init')
def receive_label_init(target, args, kwargs):
kwargs["type"] = "model_a"
@event.listens_for(FlaskModel, 'mapper_configured')
def receive_label_mapper_configured(mapper, class_):
mapper.polymorphic_identity = "model_a"