如何在定义类后设置多态标识?

时间:2013-02-27 12:37:46

标签: python python-2.7 sqlalchemy

我有一个使用Mapper Argument定义表的类:polymorphic_on: column

我有一些其他的类继承了这个类,他们都需要设置__mapper_args__ 'polymorphic_identity',我想在定义一个类之后做,而不是在类定义中设置它。

如何在定义类后设置polymorphic_identity Mapper Argument?

谢谢。

1 个答案:

答案 0 :(得分:3)

这不是完全公共API,但应该有效:

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

这是一项可以作为功能支持的内容,因此请add a feature request随意使用。

编辑:这是使用声明式的测试:

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']