Django rest framework. Deserialize json fields to

2019-05-23 02:47发布

问题:

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).

回答1:

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')