child 属性上的 SQLAlchemy 查询过滤器

SQLAlchemy query filter on child attribute

我的模型由 Parent 和 Child 以及 one-to-one 关系组成:

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 的 parents:

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 class 但我的目标是检索 Parent object.

您应该更改您的查询。

# 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))

我知道你提到过你不想查询 child class,但因为这是幕后发生的事情(SQLAlchemy 只是对你隐藏它),你也可以.然后你可以简单地通过 backref 访问 parent object。由于您指定了 lazy=joined.

,速度将完全相同
q = s.query(Child).filter(Child.value > 20)
parent_obj = q.parent