Python 所有列上的SQLAlchemy继承筛选器

Python 所有列上的SQLAlchemy继承筛选器,python,inheritance,sqlalchemy,Python,Inheritance,Sqlalchemy,因此,我想对使用表继承的数据库模型的所有列执行一个过滤器。我无法确定这是否真的可以做到 首先,让我们使用同一个继承示例,该示例来自刚刚稍加修改的。我省略了这里的导入 class Employee(Base): __tablename__ = 'employee' id = Column(Integer, primary_key=True) name = Column(String(50)) type = Column(String(50)) __mapp

因此,我想对使用表继承的数据库模型的所有
列执行一个过滤器。我无法确定这是否真的可以做到

首先,让我们使用同一个继承示例,该示例来自刚刚稍加修改的。我省略了这里的导入

class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

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

    @classmethod
    def get_all(cls, session, query):
        _filters = []
        for prop in class_mapper(cls).iterate_properties:
            if isinstance(prop, ColumnProperty):
                _col = prop.columns[0]
                _attr = getattr(cls, _cls.name)

                _filters.append(cast(_attr, String).match(query))

        result = session.query(cls)
        result = result.filter(or_(*_filters))
        return result.all()

class Engineer(Employee):
    __tablename__ = 'engineer'
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    engineer_name = Column(String(30))
    foo = Column(String(10))

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

class Manager(Employee):
    __tablename__ = 'manager'
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    manager_name = Column(String(30))
    bar = Column(String(20))

    __mapper_args__ = {
        'polymorphic_identity':'manager',
    }
现在让我们假设我想查询所有
Employee
,其中一些字段与查询匹配。上面显示的方法
get\u all
将只查询类
Employee
已知的列


有什么方法可以查询整个继承链的所有列吗?

这很难看,但有一种方法是找到从Employee继承的所有子类,然后左键联接这些表并将它们的列添加到查询中

如何获取子类:

我还没有测试过这个,但是类似的东西应该可以工作

@classmethod
def get_all(cls, session, query):
    _filters = []
    for prop in class_mapper(cls).iterate_properties:
        if isinstance(prop, ColumnProperty):
            _col = prop.columns[0]
            _attr = getattr(cls, _cls.name)

            _filters.append(cast(_attr, String).match(query))

    result = session.query(cls)
    result = result.filter(or_(*_filters))

    # get the subclasses
    subclasses = set()
    for child in cls.__subclasses__():
        if child not in subclasses:
            subclasses.add(child)
            # join the subclass
            result = result.outerjoin(child)
            # recurse to get the columns from the subclass
            result = subclass.get_all(session, result)

    # return a query, not a result to allow for the recursion. 
    # you might need to tweak this.
    return result

事实上,这相当令人讨厌,但似乎是唯一的办法。谢谢你关于使用左连接的提示