0

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?

2 Answers 2

2

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)
  • This is example code - I didn't run it

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()
Sign up to request clarification or add additional context in comments.

1 Comment

I want to do it without django model. Data arrives to me from external service and i want set rules for conversion from one json to another
1

Are you looking for something like this?

Where you overreide .to_internal_value() for deserialization and .to_representation() for serialization.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.