簡體   English   中英

SQLAlchemy繼承過濾所有列

[英]SQLAlchemy inheritance filter on all columns

所以我想對我的數據庫模型的所有Columns使用表繼承執行過濾器。 我不確定這是否真的可行。

要開始使用,請使用SQLAlchemy Doc中的相同繼承示例稍加修改。 我在這里省略了導入。

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_all方法只會查詢Employee類已知的列。

有沒有辦法在整個繼承鏈的所有列中查詢?

它非常難看,但一種方法是找到從Employee繼承的所有子類,然后將這些表連接起來並將它們的列添加到查詢中。

如何獲取子類: https//stackoverflow.com/a/5883218/443900

沒有測試過這個,但這樣的事情應該有效。

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM