Django rest框架:将字符串序列化为整数,反之亦然

时间:2018-05-15 05:29:07

标签: python django serialization django-rest-framework

我们正在使用Django Rest框架来序列化和反序列化来自第三方API的json响应。我需要将字符串字段值转换为系统中的数值。

JSON响应如下所示

{
   "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 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 framework. Deserialize json fields to different fields on the model如果将整数转换为字符串是个好主意。如何将字符串转换为int?我是django rest api和django的新手。

1 个答案:

答案 0 :(得分:2)

要显示字符串而不是int,您可以使用get_FOO_display模型的属性。要在创建过程中将字符串转换为int,您可以覆盖create()方法,如下所示:

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