Json Django Rest框架使用自定义字段将查询集序列化到字典中
我正在尝试获取这种JSON:Json Django Rest框架使用自定义字段将查询集序列化到字典中,json,django,django-rest-framework,Json,Django,Django Rest Framework,我正在尝试获取这种JSON: "Physical": { "Strength": 1, "Dexterity": 1, "Stamina": 1 }, 但对于我的自定义序列化程序: class EnumField(serializers.Field): """ Enum objects are serialized into " 'label' : value " notation
"Physical": {
"Strength": 1,
"Dexterity": 1,
"Stamina": 1
},
但对于我的自定义序列化程序:
class EnumField(serializers.Field):
"""
Enum objects are serialized into " 'label' : value " notation
"""
def to_representation(self, obj):
return {"{0}".format(obj.all()[0].__str__()): obj.all()[0].current_value}
class EnumListField(serializers.DictField):
child = EnumField()
在我的模型上:
@property
def physical_attributes(self):
return [self.attributes.filter(attribute=attribute) for attribute
in AttributeAbility.objects.physical()]
输出如下:
"mental_attributes": [
{
"Intelligence": 1
},
{
"Wits": 0
},
{
"Resolve": 0
}
],
我需要对我的字段做些什么,才能看起来像我的第一个JSON?我认为已经不存在了,这正是上面几个问题所建议的。您的属性返回一个列表,并且您需要键:值对,所以将它们视为字典:
def to_representation(self, obj):
return {str(item.get()): item.get().value for item in obj}
显然,用您想要的任何值替换.value,如果str表示形式不是您想要的键,则替换它