SQLAlchemy一对多查询

时间:2018-05-31 17:56:37

标签: python sqlalchemy

我对如何进行查询感到困惑。我有以下声明

class GrandParent(Base):
    __tablename__ = "grandparent"
    id = Column(Integer, primary_key=True)
    name = Column(String(16))
    # One-to-one relationship
    parent_id = Column(Integer, ForeignKey('parent.id'))
    parent = relationship("Parent", backref=backref("grandparent", uselist=False))

    def __init__(self, name):
        self.name = name


class Parent(Base):
    __tablename__ = "parent"
    id = Column(Integer, primary_key=True)
    name = Column(String(16))
    # One-to-many relationship
    children = relationship("Child", backref="parent")

    def __init__(self, name):
        self.name = name


class Child(Base):
    __tablename__ = "child"
    id = Column(Integer, primary_key=True)
    name = Column(String(16))
    index = Column(Integer)
    parent_id = Column(Integer, ForeignKey('parent.id'))

    def __init__(self, name, idx):
        self.name = name
        self.index = idx

    def __repr__(self):
        return self.name

我希望能够做的是查询知道其Childindex的{​​{1}}个对象。我知道这个查询不起作用,只是为了说明我正在寻找的内容:

GrandParent.id
  

属性错误:没有' InstrumentedAttribute'对象也不是   '比较器'与Child.parent关联的对象具有属性   '祖父母'

然而这有效:

c = session.query(Child).filter(Child.parent.grandparent.id == 2 and Child.index == 3).first()

1 个答案:

答案 0 :(得分:4)

最后在发布后找到了解决方案。

请参阅doc以获取参考资料

c = session.query(Child).\
        filter(Child.parent.has(Parent.grandparent.has(GrandParent.id == 2))).\
        filter(Child.index == 2).first()