python - 子属性上的 SQLAlchemy 查询过滤器

标签 python orm sqlalchemy 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 的 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/

相关文章:

python - 运行 python 脚本在 Amazon RDS 数据库实例上创建我的架构

python - Cassandra 崩溃了,不知道出了什么问题

.net - 远程还是不远程?

python - 如何将基类的映射方法用于派生类?

python - 如何使用没有 ORM 的 SQLAlchemy 查询从表中删除行?

mysql - SQLAlchemy 与 Google Cloud SQL 连接到开发服务器

python - 将一维 numpy 数组转换为列表列表

python - 有没有办法在 Cygwin 上使用 Python 3.5?

python - 在 Django 中显示/渲染静态图像的简单 View

python - SQLAlchemy 中的 Eager Inner Join