将REST API数据排序并设置为新列表

时间:2017-12-28 03:58:09

标签: python django django-rest-framework

我正在尝试基于API创建报表,但是API目前没有按我希望的那样排序,我不确定如何重新排列它。以下是API的示例:

[
    {
        "task": {
            "id": 2,
            "name": "Texturing",
        },
        "assign_to": {
            "id": 1,
            "official_name": "Roy Harper",
        },
        "duration": 3.0,
    },
    {
        "task": {
            "id": 4,
            "name": "Lighting",
        },
        "assign_to": {
            "id": 3,
            "official_name": "Donna Troy",
        },
        "duration": 4.0,
    },
    {
            "task": {
                "id": 8,
                "name": "Rendering",
            },
            "assign_to": {
                "id": 1,
                "official_name": "Roy Harper",
            },
            "duration": 7.0,
    },
    {
            "task": {
                "id": 11,
                "name": "Coloring",
            },
            "assign_to": {
                "id": 3,
                "official_name": "Donna Troy",
            },
            "duration": 5.0,
    },
{

]

我现在想要实现的是一个API列表,它集中在assign_to字段上,并且还设置了列表,因此它只填充同一个人一次。这是我想要实现的所需输出:

[
    {
        "assign_to": {
            "id": 1,
            "official_name": "Roy Harper",
        },
        "total_task"[
           "task":{
             "id": 4,
             "name": "Lighting",
           },
           "duration": 3.0,
           "task":{
             "id": 8,
             "name": "Rendering",
           },
           "duration": 7.0,
        ],
    },
    {
        "assign_to": {
            "id": 3,
            "official_name": "Donna Troy",
        },
        "total_task"[
           "task":{
             "id": 4,
             "name": "Lighting",
           },
           "duration": 4.0,
           "task": {
             "id": 11,
             "name": "Coloring",
           },
           "duration": 5.0,
        ],
    },
]

以下是我的代码:

Model.py:

class TaskOrder(models.Model):
    task = models.ForeignKey(Task, on_delete=models.CASCADE)
    assign_to = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='assign_to', null=True, blank=True)
    duration = models.FloatField(null=True, blank=True)

serializer.py:

class ReportContentSerializer(serializers.ModelSerializer):
    assign_to = AssignToSerializer()
    class Meta:
        model = WorkOrder
        fields = ('task', 'assign_to', 'duration')
        depth = 1

api.py:

class ReportContentAPI(APIView):
    def get(self, request, project_id, parent_id):
        all_taskorders = TaskOrder.objects.all().filter(content__project_id=project_id, content__parent_id=parent_id)
        report_content_serializer = ReportContentSerializer(all_taskorders, many=True)
        return Response(report_content_serializer.data)

非常感谢任何帮助。非常感谢。

0 个答案:

没有答案