序列化到namedtuple会引发“太多值无法解包”

时间:2019-05-18 17:11:48

标签: python django serialization django-rest-framework

我想使用序列化器来验证和反序列化JSON。

我尝试过:

let yourArray = [{
        amount: "123",
        category: "drinks",
        location: "NYC",
        note: "piano bar",
        receipt: "img.jpg"
    },
    {
        amount: "123",
        category: "drinks",
        location: "NYC",
        note: "piano bar",
        receipt: "img.jpg"
    },
    {
        amount: "123",
        category: "bills",
        location: "NYC",
        note: "piano bar",
        receipt: "img.jpg"
    },
    {
        amount: "123",
        category: "savings",
        location: "NYC",
        note: "piano bar",
        receipt: "img.jpg"
    }
]


var newMap = new Map();


yourArray.forEach(ele => {
    if (!newMap.get(ele.category)) {
        newMap.set(ele.category, [ele])
    } else {
        newMap.get(ele.category).push(ele)
    }
})

console.log(newMap)
newMap.forEach((value, key) => {
    console.log(`${key} ${value.length}`)
})

然后在repl中:

Candidate = namedtuple("Candidate",
    ["name", "description"]
)

class CandidateSerializer(serializers.Serializer):
    name = serializers.CharField()
    description = serializers.CharField()

    def to_internal_value(self, data):
        return Candidate(**data)

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

这不是您使用序列化器的方式。序列化器用于获取JSON并转换为Python数据类型。然后,如果要获取转换后的数据并输出诸如namedtuple之类的内容,则需要实现create()并通过save()进行调用。所以:

class CandidateSerializer(serializers.Serializer):
    name = serializers.CharField()
    description = serializers.CharField()

    def create(self, validated_data):
        return Candidate(**validated_data)

现在:

>>> s = CandidateSerializer(data={'name': "Seb", 'description':"Hello"})
>>> s.is_valid()
True
>>> s.save()
Candidate(name='Seb', description='Hello')