Reputation: 425
If I have a serializer thus:
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
then the dictionary returned by serializer.data
will have keys "email"
and "content"
.
But I need to include fields whose names are not valid Python identifiers:
"type"
"@context"
Is there an idiomatic way of doing this?
Upvotes: 0
Views: 209
Reputation: 88619
try to override to_representation()
method in CommentSerializer
as,
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": "[email protected]","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': '[email protected]', '@context': 'some content'}
Upvotes: 1