wobbily_col
wobbily_col

Reputation: 11878

Django rest framework. Deserialize json fields to different fields on the model

I have a json response from a web request which almost maps to my django model.

How do I serialize this json(preferably with a model serializer),but override one field, so I can map it to a differently named field on the Django model. (I have one field "expected_value" in the json object, but I want to map that to the "actual_value" of my Django model).

Upvotes: 3

Views: 2933

Answers (1)

pgiecek
pgiecek

Reputation: 8200

You can add extra fields to a ModelSerializer or override the default fields by declaring fields on the class, just as you would for a Serializer class.

Something like the code snippet below should work.

class MySerializer(serializers.ModelSerializer):
    expected = serializers.Field(source='actual')

    class Meta:
        model = MyModel
        fields = ('field1', 'field2', 'expected')

Upvotes: 4

Related Questions