Django Rest Framework 将查询集序列化为带有自定义字段的字典

Django Rest Framework serialize query set into dictionary with custom field

我正在尝试获得这种 JSON:

"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?我认为 不再存在,这是关于 SO 的一些问题的建议。

你的 属性 returns 一个列表,你想要 key:value 对,所以把它们当作字典:

def to_representation(self, obj):
    return {str(item.get()): item.get().value for item in obj}

显然将 .value 替换为您想要的任何值,如果 str() 表示不是您想要的密钥,请替换它。