我的模型由一对一关系的父子组成:
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
name = Column(String)
child = relationship("Child", backref="parent", uselist=False, lazy='joined')
class Child(Base):
__tablename__ = 'child'
child_id = Column(Integer, ForeignKey(Parent.id), primary_key=True)
value = Column(Integer)
我的测试数据如下:
q = s.query(Parent)
pd.read_sql(q.statement,s.bind)
id name child_id value
1 a 1 10
2 b 2 20
3 c 3 30
现在我只想使用此查询获取 child.value > 20 的 parent :
q = s.query(Parent).filter(Parent.child.value > 20)
但是出现这个错误:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object
associated with Parent.child has an attribute 'value'
当然,我可以直接查询 Child 类,但我的目标是检索 Parent 对象。
最佳答案
您应该更改您的查询。
# version-1: use JOIN
q = s.query(Parent).join(Child, Parent.child).filter(Child.value > 20)
# or:
# version-2: use EXISTS
q = s.query(Parent).filter(Parent.child.has(Child.value > 20))
关于python - 子属性上的 SQLAlchemy 查询过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40524749/