Sqlalchemy的关系

发布于 2025-01-29 12:22:13 字数 609 浏览 1 评论 0原文

我使用sqlalchemy orm和pydantic
我有以下简单的桌子

class Parent(Base):
    __tablename__ = 'parents'
    id = Column(Integer, primary_key=True, nullable=False)
    children = relationship(
        "Child",
        backref="parent",
        uselist=True
    )

class Child(Base):
    __tablename__ = 'children'
    id = Column(Integer, primary_key=True, nullable=False)
    parent.id = Column(Integer, ForeignKey(Parent.id))
    age = Column(Integer)

让父母和他们的孩子很容易
但是我该如何随着年龄的年龄过滤?
如果您得到以下内容,然后与Pydantic序列化,所有孩子都将嵌套

parents = db.query(Parent).all()

I Use sqlalchemy ORM and pydantic
I have the following simple table

class Parent(Base):
    __tablename__ = 'parents'
    id = Column(Integer, primary_key=True, nullable=False)
    children = relationship(
        "Child",
        backref="parent",
        uselist=True
    )

class Child(Base):
    __tablename__ = 'children'
    id = Column(Integer, primary_key=True, nullable=False)
    parent.id = Column(Integer, ForeignKey(Parent.id))
    age = Column(Integer)

Getting the parents and their children is easy
But how can i filter that child with age?
If you get the following and then serialize it with pydantic, all children will be nested

parents = db.query(Parent).all()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尛丟丟 2025-02-05 12:22:13

您需要在父桌和子桌之间进行连接,以便对孩子进行过滤器。

parents = db.query(Parent).join(Child, Child.parent.id == Parent.id).filter(Child.age < 18).all()

You need to do a join between your parent table and your child table to do a filter on the child.

parents = db.query(Parent).join(Child, Child.parent.id == Parent.id).filter(Child.age < 18).all()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文