How to append extra data to the existing serialize

2020-07-14 10:23发布

问题:

I am new to django rest-framework serializers.

views.py 
@csrf_exempt
@api_view(['GET'])         
def getAllAvailableEmps(request):  
    if request.method == 'GET':
        try:
            roleId = request.GET['emp_role_id']
            getEmp = emp_details.objects.filter(emp_dc_id = None,emp_active = True,emp_role_id = roleId)
            serializer = getEmpDcSerializer(getEmp,many=True)
            return JSONResponse({"allAvilableEmps":serializer.data})
        except Exception as e:
            return JSONResponse("Failure "+str(e)) 

serializers.py
class getEmpDcSerializer(serializers.ModelSerializer): 
    class Meta:
        model = emp_details
        fields = ('emp_id','emp_dc_id','emp_first_name','emp_last_name','emp_role_id')

from the above code i got the result like below

{
  "allAvilableEmps": [
    {
      "emp_id": 13,
      "emp_dc_id": [],
      "emp_first_name": "aaa",
      "emp_last_name": "bb",
      "emp_role_id": 4
    },
    {
      "emp_id": 16,
      "emp_dc_id": [],
      "emp_first_name": "cccc",
      "emp_last_name": "ddd",
      "emp_role_id": 4
    }
]
}

Here,I need to add two more fields(Available,Assign) to the JOSN data.Like below(which is not exist in the database).. So final JSON should be like below. How to achieve this ?.

{
  "allAvilableEmps": [
    {
      "emp_id": 13,
      "emp_dc_id": [],
      "emp_first_name": "aaa",
      "emp_last_name": "bb",
      "emp_role_id": 4
      "Available":1,
      "Assign":2    
    },
    {
      "emp_id": 16,
      "emp_dc_id": [],
      "emp_first_name": "cccc",
      "emp_last_name": "ddd",
      "emp_role_id": 4
      "Available":1,
      "Assign":2    
    }
  ]
}

回答1:

You can use SerializerMethodField to add extra data to the serialized representation of an object.

This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.

In your serializer, add Available and Assign SerializerMethod fields. Doing this will always add Available and Assign keys in your serialized data.

class getEmpDcSerializer(serializers.ModelSerializer): 
    Available = serializers.SerializerMethodField() # add field
    Assign = serializers.SerializerMethodField() # add field

    class Meta:
        model = emp_details
        fields = ('emp_id','emp_dc_id','emp_first_name','emp_last_name','emp_role_id', 'Available', 'Assign')

    def get_Available(self, obj):
        # here write the logic to compute the value based on object
        return 1

    def get_Assign(self, obj):
        # here write the logic to compute the value based on object
        return 2