Customize Json Response in django rest framework

走远了吗. 提交于 2019-12-06 11:07:20

There is the method called to_representation in DRF. Reference:http://www.django-rest-framework.org/api-guide/fields/

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!