【问题标题】:How to change the name of fields using SqlAlchemy-Marshmallow?如何使用 SqlAlchemy-Marshmallow 更改字段名称?
【发布时间】:2019-08-10 09:20:10
【问题描述】:

我正在使用 SQLAlchemy - Marshmallow 来创建模式,它大致如下所示:

class someModel(db.Model):
  y_x = db.Column(db.BigInteger, primary_key = True)

class someSchema(ma.ModelSchema):
  class Meta:
    model = someModel

我遇到的问题是我想要使用的 JSON 对象具有属性 x,{“x”:1},而不是 y_x。架构有没有办法识别这一点?我知道在棉花糖你可以做 y = fields.Integer(data_key="x") 但我不确定这是否适用于 Marshmallow 烧瓶,是否可以在 model = someModel 之后添加它。

【问题讨论】:

    标签: python sqlalchemy marshmallow


    【解决方案1】:

    我遇到了这个确切的问题,并试图通过在我的架构定义中添加手动字段覆盖来解决它。这在从模型自动生成的字段和我手动定义的字段之间产生了冲突。事实证明,如果您手动覆盖字段,则需要通过将它们明确标记为从 Meta 类中排除来将它们排除在推理之外。这样的事情最终对我有用:

    class FooSchema(ma.ModelSchema):
        id = fields.Integer(attribute="foo_id")
        class Meta:
           model = Foo
           exclude = ["foo_id"]
    

    希望这可以节省一些时间来挖掘 Marshmallow-SQLAlchemy 源代码。

    【讨论】:

      【解决方案2】:

      SqlAlchemy-Marshmallow 提供了一些关于如何使用 ModelSchemas 的示例,其中一个关于 Overriding generated fields 的示例符合您的需求:

      ModelSchema 生成的任何字段都可以被覆盖。

      例如,您可以简单地手动指定 field 对象的字段和 use the attribute parameter

      from marshmallow import fields
      
      class someSchema(ma.ModelSchema):
          x = fields.Integer(attribute='y') # Or vice-versa
          class Meta:
              model = someModel
      

      【讨论】:

        猜你喜欢
        • 2010-11-09
        • 2011-11-07
        • 2017-11-10
        • 2021-08-24
        • 1970-01-01
        • 2015-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多