Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append extra data to the existing serializer in django

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    
    }
  ]
}
like image 697
user1335606 Avatar asked Aug 04 '16 05:08

user1335606


People also ask

How to pass extra data to a Django REST framework serializer?

In this post, you will learn how to Pass Extra Data to a Django REST Framework Serializer and Save it to the Database. In a standard Django form, a code snippet of the procedure would look like this: form = VoterForm (request.POST) if form.is_valid (): voter = form.save (commit=False) voter.user = request.user voter.save ()

How do I create a model serializer in Django?

To do so, open the Django shell, using python manage.py shell, then import the serializer class, instantiate it, and print the object representation… If you only want a subset of the default fields to be used in a model serializer, you can do so using fields or exclude options, just as you would with a ModelForm.

How do I add extra data to a serialized object?

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.

How to pass extra context data to the serializer in Python?

To pass extra context data to the serializer we use "context" parameter. "context" parameter takes the data in the form of a dictionary. Let's take an example to understand it more clearly.


1 Answers

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
like image 103
Rahul Gupta Avatar answered Sep 18 '22 12:09

Rahul Gupta