2014-03-12 82 views
1

我有三個類代表我的模型中的不同部分:SectionA,SectionB,SectionC。 這些部分中的每一部分都關聯了一組項目(我的模型中的類別爲Item)。Django + rest-framework:序列化任意查詢

我想獲得一個類似的JSON:

{ 
"sectionA": [ 
     { 
      "id": 1, 
      "picture": "car_pic1", 
      "category": "cat1" 
     }, 
     { 
      "id": 3, 
      "picture": "car_pic1", 
      "category": "cat2" 
     }, 
     { 
      "id": 5, 
      "picture": "car_pic1", 
      "category": "cat3" 
     } 
], 
"sectionB": [ 
     { 
      "id": 2, 
      "picture": "car_pic1", 
      "category": "cat8" 
     }, 
     { 
      "id": 4, 
      "picture": "car_pic1", 
      "category": "cat9" 
     }, 
     { 
      "id": 7, 
      "picture": "car_pic1", 
      "category": "cat10" 
     }, 
], 
"sectionC": [ 
      { 
       "id": 9, 
       "picture": "car_pic1", 
       "category": "cat9" 
      }, 
      { 
       "id": 10, 
       "picture": "car_pic1", 
       "category": "cat9" 
      }, 
      { 
       "id": 11, 
       "picture": "car_pic1", 
       "category": "cat10" 
      }, 
] 
} 

此JSON顯示關聯到每個部分中的任何三個項目。

我想知道如何使用rest-framework來實現這個功能。基本上我需要執行一個查詢檢索每個部分的三個項目(因爲這個json沒有關聯到模型對象)並將所有這些序列化到json中。我不確定在哪裏或如何執行這些查詢,但迄今爲止我沒有取得任何成功。

回答

3

最後我做了一些稍微不同的事情。我的觀點僅僅是創建與每個部分一本字典及其關聯項目:

class SectionList(APIView): 
    """ 
    List three objects for each section. 
    """ 
    def generate_data(self): 
     #query to get the items of each section 

     list_items = [] 
     list_items.append({"section" : "sectionA", "items" : secA_items}) 
     list_items.append({"section" : "sectionB", "items" : secB_items}) 
     list_items.append({"section" : "sectionC", "items" : secC_items}) 

     return list_items; 

    def get(self, request, format=None): 
     section_list = self.generate_data() 
     serializer = SectionSerializer(section_list) 
     return Response(serializer.data) 

這是我使用的串行:

class SectionSerializer(serializers.Serializer): 
    section = serializers.CharField(max_length=200) 
    items = ItemSerializer(many=True)