Skip to content Skip to sidebar Skip to footer

Sqlalchemy Inheritance Filter On All Columns

So I want to execute a filter on all Columns of my Database Model which uses table inheritance. I am by no means sure if this is actually do-able or not. To get started let's use t

Solution 1:

It's pretty ugly, but one way would be to find all the subclasses that inherit from Employee, then left join those tables and add their columns to the query.

How to get subclasses: https://stackoverflow.com/a/5883218/443900

Have not tested this, but something like this should work.

@classmethoddefget_all(cls, session, query):
    _filters = []
    for prop in class_mapper(cls).iterate_properties:
        ifisinstance(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 notin 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

Post a Comment for "Sqlalchemy Inheritance Filter On All Columns"