使用棉花糖按字母顺序对字段值进行排序
Sort field values alphabetically using marshmallow
当 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)
如the docs所述:
By default, receives a single object at a time, regardless of whether many=True is passed to the 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={})
PoP 给出的答案没有解决我需要对值进行排序的事实。我是这样做的:
@post_load
def post_load_hook(self, item):
item['genres'] = sorted(item['genres'])
return item
当 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)
如the docs所述:
By default, receives a single object at a time, regardless of whether many=True is passed to the 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={})
PoP 给出的答案没有解决我需要对值进行排序的事实。我是这样做的:
@post_load
def post_load_hook(self, item):
item['genres'] = sorted(item['genres'])
return item