在Django Rest框架中自定义Json Response [英] Customize Json Response in django rest framework
问题描述
下面是我的序列化器类.我将所有字段都放在一个模型中.我想以自定义格式更改序列化器数据的表示形式.尝试使用序列化器的to_representation方法,但未成功.
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": "abcd@gmail.com",
"Order_ID": "",
"Order_Code": "",
"Item_Code": "",
"DispatchedOn": "",
"Payment_Mode": ""
},
{
"Name": "abc",
"Address_ID": "6819319",
"Portal": "amksl",
"Address": "",
"City": "absjsls",
"DisplayOrderDateTime": null,
"Email": "abcd@gmail.com",
"Order_ID": "",
"Order_Code": "",
"Item_Code": "",
"DispatchedOn": "",
"Payment_Mode": ""
},
so on....
所以我的问题是我将如何实现这种json格式.简而言之,我该如何自定义视图类
so my question is how would i achieve this json format. In short how do i customize my view class
{
"identifiers":{
"email":"abcd@gmai.com",
"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":"abcd@gmai.com",
"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
推荐答案
DRF中有一种称为 to_representation
的方法.参考: http://www.django-rest-framework.org/api-guide/fields/
There is the method called to_representation
in DRF.
Reference:http://www.django-rest-framework.org/api-guide/fields/
这篇关于在Django Rest框架中自定义Json Response的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!