2014-03-12 4 views
1

내 모델의 다른 섹션을 나타내는 세 클래스가 있습니다 : SectionA, SectionB, SectionC. 각 섹션에는 일련의 항목 (내 모델에는 Item 클래스)이 연결되어 있습니다.Django + rest-framework : 임의의 쿼리를 직렬화

{ 
"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은 각 섹션에 관련된 세 가지 항목을 표시 :이 비슷한 JSON을 좀하고 싶습니다

.

어떻게 나머지 프레임 워크를 사용하여 구현할 수 있는지 알고 싶습니다. 기본적으로 각 섹션에 대한 세 항목을 검색하는 쿼리를 수행해야하며 (이 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) 
관련 문제