简体   繁体   English

如何使用 SqlAlchemy-Marshmallow 更改字段名称?

[英]How to change the name of fields using SqlAlchemy-Marshmallow?

i'm using SQLAlchemy - Marshmallow for schema creation, it roughly looks like this:我正在使用 SQLAlchemy - Marshmallow 创建模式,它大致如下所示:

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

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

The problem I'm having is the JSON object that I want to use has the property x, {"x": 1}, not y_x.我遇到的问题是我想使用的 JSON 对象具有属性 x, {"x": 1},而不是 y_x。 Is there a way for the schema to recognize this?模式有没有办法识别这一点? I'm aware in Marshmallow you can do y = fields.Integer(data_key="x") But i'm not sure if this works with Marshmallow flask, and if you can add this after model = someModel or not.我知道在棉花糖中你可以做 y = fields.Integer(data_key="x") 但我不确定这是否适用于棉花糖烧瓶,以及你是否可以在 model = someModel 之后添加它。

I was having this exact problem and attempting to fix it by adding a manual field override to my schema definition.我遇到了这个确切的问题,并试图通过向我的模式定义添加手动字段覆盖来修复它。 This was creating a collision between the field being generated automatically from the model and the field I manually defined.这在从模型自动生成的字段和我手动定义的字段之间创建了冲突。 It turns out if you override fields manually, they need to be excluded from inference by explicitly marking them as excluded from the Meta class.事实证明,如果您手动覆盖字段,则需要通过将它们显式标记为从 Meta 类中排除来将它们从推理中排除。 Something like this ended up working for me:这样的事情最终对我有用:

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

Hope this saves somebody some time digging through Marshmallow-SQLAlchemy source.希望这可以节省一些时间来挖掘 Marshmallow-SQLAlchemy 源代码。

SqlAlchemy-Marshmallow provides few examples on how to use the ModelSchemas, one about Overriding generated fields corresponds to your needs: SqlAlchemy-Marshmallow 提供了一些关于如何使用 ModelSchemas 的示例,其中一个关于覆盖生成的字段符合您的需求:

Any field generated by a ModelSchema can be overridden. ModelSchema 生成的任何字段都可以被覆盖。

You could for example simply manually specify the field and use the attribute parameter of the field object:例如,您可以简单地手动指定字段并使用field对象attribute参数

from marshmallow import fields

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM