【问题标题】:Django + rest-framework: serialize arbitrary queryDjango + rest-framework:序列化任意查询
【发布时间】:2014-04-16 13:02:51
【问题描述】:

我的模型中有三个代表不同部分的类:SectionASectionBSectionC。 这些部分中的每一个都关联了一组项目(我的模型中的类 Item)。

我想得到一个类似这样的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 中。我不确定在哪里或如何执行这些查询,到目前为止我没有任何成功。

【问题讨论】:

    标签: json django rest django-rest-framework


    【解决方案1】:

    最后我做的有点不同。我的观点只是为每个部分及其相关项目创建了一个字典:

    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)
    

    【讨论】:

      猜你喜欢
      • 2013-07-04
      • 1970-01-01
      • 2023-03-30
      • 2015-06-29
      • 2015-01-12
      • 2016-07-21
      • 2015-12-13
      • 2014-01-31
      • 1970-01-01
      相关资源
      最近更新 更多