Django rest框架。将json字段反序列化为模型上的不同字段 [英] Django rest framework. Deserialize json fields to different fields on the model
问题描述
我有一个来自Web请求的json响应,该响应几乎映射到我的Django模型。
I have a json response from a web request which almost maps to my django model.
我如何序列化此json(最好使用模型序列化器),但是要覆盖一个字段,因此我可以将其映射到Django模型上一个不同名称的字段。 (我在json对象中有一个字段 expected_value,但我想将其映射到我的Django模型的 actual_value)。
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).
推荐答案
您可以在
ModelSerializer $ c中添加额外的字段$ c>或通过在类中声明字段来覆盖默认字段,就像对
Serializer
类的使用一样。
You can add extra fields to a
ModelSerializer
or override the default fields by declaring fields on the class, just as you would for aSerializer
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')
这篇关于Django rest框架。将json字段反序列化为模型上的不同字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!