如果我有序列化器,则:
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
然后,serializer.data
返回的字典将具有键"email"
和"content"
。
但是我需要包括其名称不是有效的Python标识符的字段:
"type"
"@context"
是否有惯用的方法?
答案 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'}