sqlalchemy中的轻型申请版本

发布于 2025-01-26 00:52:55 字数 544 浏览 1 评论 0原文

我有以下模型:

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

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    ...

每个类都有更多属性。孩子们总是首先创造的。在我的API中,我想发送帖子请求,以创建带有X子女的父母。对于只有几个孩子,我希望所有具有所有属性的子对象都在请求主体中。但是可能有一个用例,父母有100个孩子。对于这些,我想实现一个“轻”版本,在该请求主体中只有每个孩子的ID,而不是每个孩子的所有属性的整个对象。

是否有内置的方式,示例或官方术语来实现这种行为?我在谷歌搜索Light请求Sqlalchemy,但Choulnd并没有真正发现很多。

I have the following models:

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

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    ...

There are more attributes for each class. The children are always created first. In my api, I want to send POST requests that creates a Parent with x amount of children. For just a few children, I want the complete child object with all attributes to be in the request body. But there could be a use case where a parent has 100 children. For those, I want to implement a "light" version, where in the request body there would only be the id of each child, instead of the entire object with all attributes for each child.

Is there a built-in way or an example or an official term for such a behavior? I was googling light requests sqlalchemy but choulnd't really find much.

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

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

发布评论

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

评论(1

那片花海 2025-02-02 00:52:55

我认为没有您想要的内置机制,因为这不是请求您的对象如何序列化的责任。对于您的情况,我将实施这样的事情:

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    other_attr = Column(String)

    def to_dict(self, is_light = False):
       if is_light:
          return {"id": seld.id}
       else:
          return {"id": self.id, "other_attr": self.other_attr}

I think that there is not built-in mechanism of what you desire, because it is not a responsibility of a request how your objects are serialized. For your case I would implement something like that:

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    other_attr = Column(String)

    def to_dict(self, is_light = False):
       if is_light:
          return {"id": seld.id}
       else:
          return {"id": self.id, "other_attr": self.other_attr}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文