定义类后如何设置多态标识? [英] How can I set Polymorphic Identity after a class is defined?
问题描述
我有一个用映射器参数定义表的类:polymorphic_on: column
I have a Class defining a table with Mapper Argument: polymorphic_on: column
我有一些继承这个类的其他类,它们都需要设置 __mapper_args__ 'polymorphic_identity'
,我想在定义一个类而不是在类定义中设置它之后这样做.
I have some other Classes inhering this class and they all need to set __mapper_args__ 'polymorphic_identity'
, which I would like to do after a class is defined instead of having it set within the Class definition.
定义类后如何设置 polymorphic_identity Mapper Argument?
How can I set polymorphic_identity Mapper Argument after a class is defined?
谢谢.
推荐答案
这不是完全公开的 API 但应该可以工作:
this is not totally public API but should work:
from sqlalchemy.orm import class_mapper
mapper = class_mapper(MySubClass)
mapper.polymorphic_identity = "some_identity"
mapper.polymorphic_map["some_identity"] = mapper
# in 0.8, might try to fix this for 0.9
mapper._identity_class = mapper.inherits._identity_class
这是可以作为功能支持的功能,因此请随时添加功能请求.
this is something that can be supported as a feature so feel free to add a feature request.
这是一个使用声明的测试:
here's a test using declarative:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import class_mapper
Base= declarative_base()
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
type = Column(String)
__mapper_args__ = {"polymorphic_on": type, "polymorphic_identity": "a"}
class B(A):
pass
mapper = class_mapper(B)
mapper.polymorphic_identity = "b"
mapper.polymorphic_map["b"] = mapper
e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
s = Session(e)
s.add_all([A(), B(), B(), A(), A()])
s.commit()
s.close()
assert [obj.type for obj in s.query(B).order_by(A.id)] \
== ['b', 'b']
assert [type(obj) for obj in s.query(B).order_by(A.id)] \
== [B, B]
assert [obj.type for obj in s.query(A).order_by(A.id)] \
== ['a', 'b', 'b', 'a', 'a']
这篇关于定义类后如何设置多态标识?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!