使用marshmallow按字母顺序对字段值进行排序

3
我需要在API返回值时为每个字段按字母顺序排序。似乎marshmallow的pre_dump方法是在序列化之前预处理数据的方法,但我还没有搞清楚。我已经多次阅读了文档并进行了谷歌搜索,但没有找到答案。
class UserSettingsSchema(UserSchema):
    class Meta:
        fields = (
            "id",
            "injuries",
            "channel_levels",
            "movement_levels",
            "equipments",
            "goals",
            "genres"
        )

    @pre_dump
    def pre_dump_hook(): # what do I pass in here?
        # alphabetize field values, eg, all the genres will be sorted

    equipments = fields.Nested(EquipmentSchema, many=True)
    goals = fields.Nested(GoalSchemaBrief, many=True)
    genres = fields.Nested(GenreSchemaBrief, many=True)

如果这是您问题的答案,请接受它,否则请留下评论说明为什么它不能回答您的问题。 - PoP
2个回答

4
PoP的答案未解决我需要排序值的问题。这是我实现的方法:
@post_load
def post_load_hook(self, item):
    item['genres'] = sorted(item['genres'])
    return item

0

文档所述:

默认情况下,无论是否将many=True传递给Schema,都会一次接收一个对象。

以下是一个示例:

from marshmallow import *

class MySchema(Schema):

    name = fields.String()

    @pre_dump
    def pre_dump_hook(self, instance):
        instance['name'] = 'Hello %s' % instance['name']

现在你可以做:

schema = MySchema()
schema.dump({'name': 'Bill'})

>>> MarshalResult(data={'name': 'Hello Bill'}, errors={})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接