Django rest框架:将字符串反序列化为整数,反之亦然 [英] Django rest framework: De serializing a string to an integer and vice versa
问题描述
我们正在使用Django Rest框架对来自第三方API的json响应进行序列化和反序列化.我需要在系统中将字符串字段值转换为数字值.
We are using Django Rest framework to serialise and deserialise json response from a third party API. I need to translate the string field values to a numeric value in our system.
JSON响应在下面给出
The JSON response is given below
{
"result": "win" # Other values include "loss"/"inconclusive"/"pending"
}
Django模型
class Experiment(Model):
RESULTS = (
(1, 'win'),
(2, 'loss'),
(3, 'inconclusive'),
)
inferred_result = models.IntegerField(choices=RESULTS, null=True, blank=True)
Django序列化程序类
Django Serializer Class
class ResultsSeializer(serializers.ModelSerializer):
# Need to convert "result" from "string" to "int" and vice versa.
class Meta:
model = models.Experiment
我想将 inferred_result
整数值转换为等效的 string
,反之亦然.我可以使用这种方法: Django rest框架.如果将整数转换为字符串是个好主意,则将json字段反序列化为模型上的不同字段.如何将字符串转换为int?我是django rest api和django的新手.
I want to convert the inferred_result
integer value to string
equivalent and vice versa. I could use this approach: Django rest framework. Deserialize json fields to different fields on the model if this is a good idea to convert integers to string. How do I convert string to int? I am new to django rest api and django.
推荐答案
要显示字符串而不是int,可以使用 create()
这样的方法:
To display string instead of int you can use get_FOO_display
model's attribute. To convert string to int during creation process you can override create()
method like this:
class ResultsSeializer(serializers.ModelSerializer):
inferred_result = serializers.CharField(source='get_inferred_result_display')
class Meta:
model = models.Experiment
fields = ('inferred_result',)
def create(self, validated_data):
dispplayed = validated_data.pop('get_inferred_result_display')
back_dict = {k:v for v, k in models.Experiment.RESULTS}
res = back_dict[dispplayed]
validated_data.update({'inferred_result': res})
return super(ResultsSeializer, self).create(validated_data)
如果需要,您需要以相同的方式覆盖 update()
.
Same way you need to override update()
if you need.
这篇关于Django rest框架:将字符串反序列化为整数,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!