Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

python - Django rest framework: De serializing a string to an integer and vice versa

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.

The JSON response is given below

{
   "result": "win" # Other values include "loss"/"inconclusive"/"pending"
}

Django Model

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

Same way you need to override update() if you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...