[英]DRF deserializing data from API to django model
I'm using serializers of django-rest-framework (DRK)我正在使用 django-rest-framework (DRK) 的序列化程序
I'm fetch data from an external API, and I want to convert this datas into an internal model (here Period)我从外部 API 获取数据,我想将这些数据转换为内部 model(此处为句点)
The thing is that the field's format of the external api are like this:问题是外部api的字段格式是这样的:
{"DateFrom": "2020-02-10T00:00:00"}
I want to rename into " date_from " field.我想重命名为“ date_from ”字段。
Here what I tried:这是我尝试过的:
Serializer:序列化器:
class PeriodSerializer(serializers.ModelSerializer):
date_from = serializers.DateTimeField(write_only=True, source='DateFrom')
class Meta:
model = Period
fields = ('date_from',)
Notice that I tried with " write_only=True, source='DateFrom'
"请注意,我尝试使用“
write_only=True, source='DateFrom'
”
And then in my code:然后在我的代码中:
json = {"DateFrom": "2020-02-10T00:00:00"}
serializer = PeriodSerializer(data=json)
serializer.is_valid() # This is returning False
print(serializer.errors)
And then the output is:然后 output 是:
{'date_from': [ErrorDetail(string='This field is required.', code='required')]}
How handle that?怎么处理? (in the best way (good practice))
(以最佳方式(良好做法))
I think you have something backwards here.我认为你在这里有一些倒退。 Given your model and what you expose in your API, you would want to do:
鉴于您的 model 以及您在 API 中公开的内容,您需要执行以下操作:
class PeriodSerializer(serializers.ModelSerializer):
DateFrom = serializers.DateTimeField(write_only=True, source='date_from')
source
specifies the data source on the model, while the name of the serializer field is what the field will be named when serialized. source
指定 model 上的数据源,而序列化器字段的名称是序列化时该字段的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.