在 django rest 框架中自定义 Json 响应
Customize Json Response in django rest framework
下面是我的序列化器 class。我有一个 model.I 中的所有字段想更改自定义格式的序列化程序数据的表示。尝试了序列化程序的 to_representation 方法但未能成功。
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',........]
所以在我看来class定义和对应的输出也在这里提到。
class MyListAPIView(ListAPIView):
def list(self,request):
queryset=MyModel.objects.all()
serializer=MyListSerilizer(queryset,many=True)
return Response({'Records':serializer.data})
输出:------------>对应view是
"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 格式。简而言之,我如何自定义视图 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/
覆盖序列化器中的to_representation方法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
无论何时调用serializer.data,都会返回这个表示字典
下面是我的序列化器 class。我有一个 model.I 中的所有字段想更改自定义格式的序列化程序数据的表示。尝试了序列化程序的 to_representation 方法但未能成功。
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',........]
所以在我看来class定义和对应的输出也在这里提到。
class MyListAPIView(ListAPIView):
def list(self,request):
queryset=MyModel.objects.all()
serializer=MyListSerilizer(queryset,many=True)
return Response({'Records':serializer.data})
输出:------------>对应view是
"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 格式。简而言之,我如何自定义视图 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/
覆盖序列化器中的to_representation方法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
无论何时调用serializer.data,都会返回这个表示字典