簡體   English   中英

SQLAlchemy一對多查詢

[英]SQLAlchemy One-to-Many query

我對如何進行查詢感到困惑。 我有以下聲明

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

我想做的就是查詢一個知道其indexGrandParent.idChild對象。 我知道此查詢不起作用,只是為了說明我在尋找什么:

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

AttributeError:與Child.parent關聯的'InstrumentedAttribute'對象和'Comparator'對象均沒有屬性'grandparent'

但這有效:

grandparent = GrandParent('dad')
grandparent.parent = Parent('bob')
grandparent.parent.children.append(Child('alice', 1))
grandparent.parent.children.append(Child('jo', 2))
grandparent.parent.children.append(Child('blo', 3))
foo = Child('foo', 4)
grandparent.parent.children.append(foo)
session.add(grandparent)
print(foo.grandparent.parent.id)

發布后終於找到了解決方法。

請參閱文件以供參考

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM