sqlalchemy polymorhic\u身份无效

2024-10-03 15:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对具有多个继承的python类使用多态\u:

engine = create_engine(
    'mysql://xxx:yyy@localhost:3306/zzz?charset=utf8&use_unicode=0',
    pool_recycle=3600, echo=True)

Base = declarative_base()

class AbstractPersistent(object):
    version = Column('VERSION', Integer)
    last_modified_by = Column('LAST_MODIFIED_BY', String(255))
    last_modified_date = Column('LAST_MODIFIED_DATE', Date)
    created_by = Column('CREATED_BY', String(255))
    created_date = Column('CREATED_DATE', Date)

class AbstractNamed(AbstractPersistent):
    eid = Column('ENTERPRISE_ID', String(255))
    title = Column('TITLE', String(255))
    description = Column('DESCRIPTION', String(255))

class AbstractContainer(AbstractNamed):
    __tablename__ = 'CM_MEMBER_CONTAINER_T'    
    id = Column('MEMBER_CONTAINER_ID',Integer,primary_key=True)
    discriminator = Column('CLASS_DISCR', String(100))
    __mapper_args__ = {'polymorphic_on': discriminator }

class CourseSet(Base,AbstractContainer):
    __mapper_args__ = {'polymorphic_identity': 'org.sakaiproject.coursemanagement.impl.CourseSetCmImpl'}

如您所见,CourseSet包含其父级的所有列,并将列CLASS_DISCR设置为'org.sakaiproject.coursemanagement.impl.CourseSetCmImpl'。你知道吗

但是当它对所有CourseSet进行查询时:

Session = sessionmaker(bind=engine)
session = Session()
course_sets = session.query(CourseSet).all()
print(course_sets)

它返回'CM_MEMBER_CONTAINER_T'的所有条目,但我只希望CLASS_DISCR设置为'org.sakaiproject.coursemanagement.impl.CourseSetCmImpl'的条目

有什么想法吗?你知道吗


Tags: orgtruestringcontainercolumnengineclassmember
1条回答
网友
1楼 · 发布于 2024-10-03 15:30:54

多亏了Michael on the google group sqlalchemy,这就是答案:

AbstractContainer is not mapped, its a mixin, so its __mapper_args__ are not used until a subclass of Base is invoked, which starts up a declarative mapping. Your only mapped class then is CourseSet, which has its own __mapper_args__ , that override those of AbstractContainer - they are ignored.

To combine __mapper_args__ from a mapped class with those of a mixin, see the example at http://www.sqlalchemy.org/docs/orm/extensions/declarative.html?highlight=declarative#combining-table-mapper-arguments-from-multiple-mixins It uses __table_args__ but the same concept of creating a full dictionary of arguments applies for __mapper_args__ as well.

相关问题 更多 >