How to serialize a Marshmallow field under a different name
https://marshmallow.readthedocs.io/en/2.x-line/quickstart.html#specifying-attribute-names
Even though the docs are for version 2, this seems to still work as of 3.5.1. The stable version 3 docs will not have this example.
class ApiSchema(Schema):
class Meta:
strict = True
_time = fields.Number(attribute="time")
_id = fields.String(attribute="id")
The accepted answer (using attribute
) didn't work for me, possibly because:
Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use data_key instead.
However data_key
worked nicely:
class ApiSchema(Schema):
class Meta:
strict = True
_time = fields.Number(data_key="time")
_id = fields.String(data_key="id")