SQLAlchemy:load_only不适用于别名继承模型

时间:2014-12-01 15:30:40

标签: python sqlalchemy

SQLAlchemy:load_only不适用于别名继承模型。 我正在使用此查询:

EngineerAlias = aliased(Engineer)
q = (session.query(EngineerAlias)
    .options(Load(EngineerAlias).load_only('id', 'profile')))
print q.all()

我收到了一个例外:

NoSuchColumnError: "Could not locate column in row 
                    for column '%(140249955138512 anon)s.employees__type'"

但是,这样的查询效果很好:

session.query(Engineer)\
.options(Load(Engineer).load_only('id', 'profile'))\
.all()

我知道这个问题与继承鉴别器_type有关,如果我将它添加到load_only列表,一切都会有效。但我几乎不想这样做,因为在我的代码中它会是一个丑陋的黑客(有点"如果它是继承模型,那么添加" _type"以及load_only列表,否则......" )。

任何人都可以提出一种方法,如何通过别名派生模型进行查询,而无需在load_only列表中添加鉴别器?

数据集:

class Employee(Model):
    __tablename__ = 'employees'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(1000))
    _type = Column(String(50))  # discriminator

    __mapper_args__ = {
            'polymorphic_on': _type,
            'polymorphic_identity': 'employee',
            }


class Engineer(Employee):
    __tablename__ = 'engineers'

    id = Column(Integer,
            ForeignKey('employees.id'),
            primary_key=True,
            )
    profile = Column(String(1000))

    __mapper_args__ = {
            'polymorphic_identity': 'engineer',
            }

1 个答案:

答案 0 :(得分:1)