django-rest-framework ModelSerializer字段,其名称是无效的Python标识符

时间:2018-07-29 19:21:16

标签: python django django-rest-framework

如果我有序列化器,则:

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)

然后,serializer.data返回的字典将具有键"email""content"

但是我需要包括其名称不是有效的Python标识符的字段:

  • "type"
  • "@context"

是否有惯用的方法?

1 个答案:

答案 0 :(得分:1)

尝试覆盖to_representation()中的CommentSerializer方法,

class CommentSerializer(serializers.Serializer):
    type = serializers.EmailField()
    content = serializers.CharField(max_length=200)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        return_data = {}
        return_data.update({"type": data['type'], "@context": data['content']})
        return return_data



EX:

In [2]: mydata = {"type": "myemail@gmail.com","content": "some content"}

In [3]: comment = CommentSerializer(data=mydata)

In [4]: comment.is_valid(True)
Out[4]: True

In [5]: comment.data
Out[5]: {'type': 'myemail@gmail.com', '@context': 'some content'}