I want to convert raw JSON:
{'code': 1, 'inner': {'x': 1, 'y': 1}}
To rendered serializer.data:
{'code': 1, 'inner_x': 1, 'inner_y': 1}
with django REST framework serializer.
Which code should be placed in serializer?
I think that it is better to have same structure in both server and client. You can create a class with x,y members named "Inner" and "inner" can be foreign key member in your original class.
To answer the question, you can override create function:
class InnerSerializer(serializers.ModelSerializer):
class Meta:
model = Inner
fields = ('x', 'y')
class CostumeSerializer(serializers.ModelSerializer):
inner = InnerSerializer()
class Meta:
model = MyModel
fields = ('code', 'inner')
def create(self, validated_data):
inner = validated_data.pop('inner')
return MyModel.objects.create(inner_x=inner.get('x', None), inner_y=inner.get('y', None), **validated_data)
EDIT: Take a look here
You can define the InnerSerializer with no model like this:
from rest_framework import serializers
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
Are you looking for something like this?
Where you overreide .to_internal_value() for deserialization and .to_representation() for serialization.