how can I add field in serializer?

2019-09-21 04:19发布

问题:

Below is my serializer.py file:

from rest_framework import serializers

class TaskListSerializer(serializers.Serializer):
    id = serializers.CharField()
    user_id = serializers.CharField()
    status = serializers.CharField()
    name = serializers.CharField()

In Python shell, I input this:

>>> from serializer import TaskListSerializer as ts

>>> result = ts({'id':1, 'user_id': 1, 'status':2, 'name': 'bob'})

>>> result.data

{'status': u'2', 'user_id': u'1', 'id': u'1', 'name': u'bob'}  

Now I want do this:

First, the input is not change, is also {'id':1, 'user_id': 1, 'status':2, 'name': 'bob'}

But I want to add a field and change name: bob to jim in serializer.py and make output like this:

{'status': u'2', 'user_id': u'1', 'id': u'1', 'name': u'jim', u'age': '15'}

How can I do it in serializer.py?

回答1:

Use serializers.SerializerMethodField()

class TaskListSerializer(serializers.ModelSerializer):
complex_things = serializers.SerializerMethodField()

    def get_complex_things(self, obj):
        result_of_complex_things = 2 + 2
        return result_of_complex_things