gpt4 book ai didi

python - 所有列上的 SQLAlchemy 继承过滤器

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:58 26 4
gpt4 key购买 nike

因此,我想对使用表继承的数据库模型的所有 执行过滤器。我绝对不确定这是否真的可行。

首先让我们使用来自 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

关于python - 所有列上的 SQLAlchemy 继承过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32561562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com