代码之家  ›  专栏  ›  技术社区  ›  user6847618

在django rest框架中自定义Json响应

  •  4
  • user6847618  · 技术社区  · 7 年前

    下面是我的序列化程序类。我在一个模型中有所有字段。我想以自定义格式更改序列化程序数据的表示。尝试使用序列化程序的表示方法,但未能成功。

    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 MyListAPIView(ListAPIView):
          def list(self,request):
              queryset=MyModel.objects.all()
              serializer=MyListSerilizer(queryset,many=True)
              return Response({'Records':serializer.data})
    

    输出:--------->对应视图为

      "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格式。简而言之,如何自定义视图类

         {
          "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
    
    2 回复  |  直到 7 年前
        1
  •  6
  •   Iyvin Jose    7 年前

    推翻 序列化程序类中的方法

    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
    

    无论何时调用序列化程序。数据,将返回此表示字典

        2
  •  1
  •   Hardik Gajjar    7 年前

    to_representation 在DRF中。 参考: http://www.django-rest-framework.org/api-guide/fields/