Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize Json Response in django rest framework

Given below is my serializer class. I have all fields in one model.I would like to change the representation of serializer data in custom format. Tried to_representation method of serializer but could not success.

class MyListSerilizer(ModelSerializer):
  class Meta:
    model=MyModel
    fields=['Name','Address_ID','Portal','Address','City','DisplayOrderDateTime','Email','Order_ID','Order_Code','Item_Code','DispatchedOn','Payment_Mode','Shipping_Charge','ShippingMethodCode','ShippingMethodCharges','CashOnDeliveryCharges','CurrencyCode','BillingAddress','GiftWrapCharges','SaleOrderItemCode','Shipping_ref','Cancellable','OnHold','Quantity','Invoice_No''Portal',........]

So in my view class defined and output corresponding to them also mentioned over here.

   class MyListAPIView(ListAPIView):
      def list(self,request):
          queryset=MyModel.objects.all()
          serializer=MyListSerilizer(queryset,many=True)
          return Response({'Records':serializer.data})

Output :---------->Corresponding to view is

  "Records": [
    {
        "Name": "abc",
        "Address_ID": "6819319",
        "Portal": "amksl",
        "Address": "",
        "City": "absjsls",
        "DisplayOrderDateTime": null,
        "Email": "[email protected]",
        "Order_ID": "",
        "Order_Code": "",
        "Item_Code": "",
        "DispatchedOn": "",
        "Payment_Mode": ""
     },
      {
         "Name": "abc",
        "Address_ID": "6819319",
        "Portal": "amksl",
        "Address": "",
        "City": "absjsls",
        "DisplayOrderDateTime": null,
        "Email": "[email protected]",
        "Order_ID": "",
        "Order_Code": "",
        "Item_Code": "",
        "DispatchedOn": "",
        "Payment_Mode": ""
     },
      so on....

so my question is how would i achieve this json format. In short how do i customize my view class

     {
      "identifiers":{
                "email":"[email protected]",
                "phone":"123664"
              },
"activity_type": "purchase",
"timestamp": "UNIX TIMESTAMP",                
"products": [{
                "brandName": "abc",
                "id": "1",                                  
                "sku": "abcd",                                
                "name": "mnis",                           
                "price": 12.9,
                "discount": "",
                "quantity": "",
                "currency": ""
                 }]
"cart_info":{
                "total":"",
                "revenue":"",
                "currency":""
            },
"Order_info":{
               "total":"2121",
                .
                .
                .
             }
  },
   {
      "identifiers":{
                "email":"[email protected]",
                "phone":"123664"
              },
"activity_type": "purchase",
"timestamp": "UNIX TIMESTAMP",                
"products": [{
                "brandName": "abc",
                "id": "1",                                  
                "sku": "abcd",                                
                "name": "mnis",                           
                "price": 12.9,
                "discount": "",
                "quantity": "",
                "currency": ""
                 }]
"cart_info":{
                "total":"",
                "revenue":"",...so on
like image 397
user6847618 Avatar asked Mar 09 '23 11:03

user6847618


1 Answers

override to_representation method in the serializer class

class MyListSerilizer(ModelSerializer):

     class Meta:
        model=MyModel
        fields=['Name','Address_ID','Portal','Address','City','DisplayOrderDateTime','Email','Order_ID','Order_Code','Item_Code','DispatchedOn','Payment_Mode','Shipping_Charge','ShippingMethodCode','ShippingMethodCharges','CashOnDeliveryCharges','CurrencyCode','BillingAddress','GiftWrapCharges','SaleOrderItemCode','Shipping_ref','Cancellable','OnHold','Quantity','Invoice_No''Portal',........]


     def to_representation(self, instance):
         # instance is the model object. create the custom json format by accessing instance attributes normaly and return it


        identifiers = dict()
        identifiers['email'] = instance.Email
        identifiers['phone'] = instance.phone

        representation = {
            'identifiers': identifiers,
            'activity_type': instance.xxxx,
            'timestamp': instance.xxxxx,
            .
            .
            .  -> your custom data
         } 

     return representation

whenever you call serializer.data, this representation dictionary will be returned

like image 78
Iyvin Jose Avatar answered Mar 11 '23 17:03

Iyvin Jose