如何序列化 JSON 从 Django 中的序列化程序请求数据?
How to serialize JSON Request data from serializer in Django?
我正在尝试通过 serializers.Serializer
序列化一个 json 数据
{
"data": {
"phoneNumber": "1234567890",
"countryCode": "+11",
"otp": "73146",
}
}
消毒器class我为它写的
class VerifyOtpSerializer(serializers.Serializer):
phone_number = serializers.CharField(max_length=225, source='phoneNumber', required=True)
country_code = serializers.CharField(max_length=225, source='countryCode', required=True)
otp = serializers.CharField(max_length=255, required=True)
还有
我不知道为什么源不工作,我尝试了下图中的JSON,但它仍然说该字段是必需的
source
value 是传递的值的键将被更改的内容。所以 source
值应该在你的 Model
.
上
The name of the attribute that will be used to populate the field.
您真正想要的是将驼峰式有效负载更改为蛇式案例的东西。只需使用 djangorestframework-camel-case 并从序列化程序字段中删除 source
。
您的请求中的密钥有误。正如汤姆所说,源应该是模型对象的一个属性。所以你必须匹配请求和序列化器中的键
更改 phoneNumber
> phone_number
更改 countryCode
> country_code
您发送给序列化程序的响应对象是正确的。您的请求对象的键应该与您在序列化程序中定义的完全相同。
尝试将其发送到您的序列化程序。
{
"data" : {
"phone_number":"1234567890",
"country_code":"+11",
"otp":"73146"
}
}
我正在尝试通过 serializers.Serializer
序列化一个 json 数据{
"data": {
"phoneNumber": "1234567890",
"countryCode": "+11",
"otp": "73146",
}
}
消毒器class我为它写的
class VerifyOtpSerializer(serializers.Serializer):
phone_number = serializers.CharField(max_length=225, source='phoneNumber', required=True)
country_code = serializers.CharField(max_length=225, source='countryCode', required=True)
otp = serializers.CharField(max_length=255, required=True)
还有
我不知道为什么源不工作,我尝试了下图中的JSON,但它仍然说该字段是必需的
source
value 是传递的值的键将被更改的内容。所以 source
值应该在你的 Model
.
The name of the attribute that will be used to populate the field.
您真正想要的是将驼峰式有效负载更改为蛇式案例的东西。只需使用 djangorestframework-camel-case 并从序列化程序字段中删除 source
。
您的请求中的密钥有误。正如汤姆所说,源应该是模型对象的一个属性。所以你必须匹配请求和序列化器中的键
更改 phoneNumber
> phone_number
更改 countryCode
> country_code
您发送给序列化程序的响应对象是正确的。您的请求对象的键应该与您在序列化程序中定义的完全相同。
尝试将其发送到您的序列化程序。
{
"data" : {
"phone_number":"1234567890",
"country_code":"+11",
"otp":"73146"
}
}