这是我尝试解决 2 天但没有成功的以下问题:
class Parent(Base):
__tablename__ = 'Parent'
__table_args__ = {'schema': 'Schema', 'extend_existing': True}
Id = Column(Integer, primary_key=True)
Name = Column(String(255))
class Child(Base):
__tablename__ = 'Child'
__table_args__ = (UniqueConstraint('ParentId', 'Name'),
{'schema': 'Schema', 'extend_existing': True})
Id = Column(Integer, primary_key=True)
ParentId = Column(Integer, ForeignKey('Schema.Parent.Id'))
Name = Column(String(255))
parent = relationship('Parent', uselist=False, viewonly=True,
backref='children')
@hybrid_property
def ChildResourceId(self):
return self.parent.Name + '-' + self.Name
@ChildResourceId.expression
def ChildResourceId(cls):
# This is the main issue:
# Which is the proper expression
# for this hybrid property
child = session.query(Child).filter_by(ChildResourceId='parent_name1-child_name1').one()
# Returns child with Id: 1
child = session.query(Child).filter_by(ChildResourceId='parent_name2-child_name1').one()
# Also returns child with Id: 1
这里的想法是使用 parent.Name 和 child.Name 的组合作为搜索条件。 我想使用混合功能而不是显式连接查询或额外的选择来完成它。
我用 concat 函数或简单的 cls 表达式尝试了多个表达式,例如:
return cls.parent.Name + '-' + cls.Name
但这些在我的情况下不起作用,因为正如您在代码片段中看到的那样 - 查询仅按 child.Name 执行查找并忽略 parent.Name。
最佳答案
似乎“select”表达式本身是不够的,需要“where”子句。 “label”将返回可选标量(子查询),并为特定的 sql 表达式添加额外的标记。
这是一种可能的解决方案:
@ChildResourceId.expression
def ChildResourceId(cls):
return select([Parent.Name + '-' + cls.Name]).\
where(Parent.Id == cls.ParentId).label('resource_id')
关于python - SQLAlchemy 混合表达式连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33940433/