在Django REST API中添加数组名称

时间:2017-06-19 08:00:30

标签: javascript python html json rest

我有一个看起来像这样的REST API

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "assign_to": 21,
        "task": 2,
        "start_date": null,
        "end_date": null
    },
    {
        "assign_to": 3,
        "task": 1,
        "start_date": "2017-06-15",
        "end_date": "2017-06-19"
    },
    {
        "assign_to": 3,
        "task": 8,
        "start_date": "2017-06-01",
        "end_date": "2017-06-08"
    }
]

现在我想将这些数据加载到DHTMLX甘特图中,但它需要在数组名{"data": []}内,所以它看起来像这样

{"data": [
    {
        "assign_to": 21,
        "task": 2,
        "start_date": null,
        "end_date": null
    },
    {
        "assign_to": 3,
        "task": 1,
        "start_date": "2017-06-15",
        "end_date": "2017-06-19"
    },
    {
        "assign_to": 3,
        "task": 8,
        "start_date": "2017-06-01",
        "end_date": "2017-06-08"
    }
 ]
}

否则DHTMLX无法识别JSON文件。那怎么能这样呢? 以下是我的代码

serializer.py

class GanttChartSerializer(serializers.ModelSerializer):
    class Meta:
        model = WorkOrder
        fields = ('assign_to', 'task', 'start_date', 'end_date')

API.py

class GanttChartList(APIView):
    def get(self, request, content_id, format=None):
        model_object = WorkOrder.objects.all().filter(parent_project_content=content_id)
        serializer = GanttChartSerializer(model_object, many=True)
        return Response(serializer.data)

    def post(self, request, content_id, format=None):
        serializer = GanttChartSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

的Javascript

gantt.config.columns = [
            {name: "assign_to", label: "Assign To", align: "left", width: 70},
        ];

    function initializeGantt() {

    gantt.init("my_scheduler");
    gantt.load("/dashboard/ganttchart_list/5/?format=json");

HTML

<div id="my_scheduler" style='width:1405px; height:245px;'></div>

非常感谢任何帮助

2 个答案:

答案 0 :(得分:2)

您应该可以通过更改传递给Response()构造函数的内容来完成此操作,如下所示:

return Response({"data": serializer.data})

根据Response的Django Rest Framework文档页面,构造函数将接受任何Python原语。

答案 1 :(得分:1)

您可以使用{"data":[]}包装json文件,并让gantt解析它:

gantt.config.columns = [
            {name: "assign_to", label: "Assign To", align: "left", width: 70},
        ];

    function initializeGantt() {

    gantt.init("my_scheduler");
    $.get("/dashboard/ganttchart_list/5/?format=json", function(data) {
            gantt.parse({'data':data});
        });