如何修改django-rest-framework API

时间:2018-03-25 08:08:50

标签: python django api django-rest-framework

我有API。我想改变它所以它看起来像这样:

[
    cats: [{
            "id": 1,
            "description": "I lost my mind",
            "petName": "kappies",
            "phone": 56765665464
        },
        {
            "id": 2,
            "description": "I lost my dog somewhere",
            "petName": "Doggy",
            "phone": 38093716438
        }
    ],
    dogs: [{
            "id": 3,
            "description": "",
            "petName": "",
            "phone": 0
        }, 
        {
            "id": 3,
            "description": "",
            "petName": "",
            "phone": 0
        }
    ]
]

谁知道我该怎么做?

我是否需要分别为猫狗创建API?

为了杯子而啜饮。 serializers

1 个答案:

答案 0 :(得分:1)

假设你的模型中有type字段。

然后,您可以在view.py

中执行此类操作
posts = models.Post.objects.all()
posts_serializer = serializers.PostSerializer(posts, many=True)

output = {}
for post in posts_serializer.data:
    type = output.get(post['type'], [])
    output[type].append(post)

return Response(output)

您应该添加更多代码以及下次提问时尝试执行的操作。

祝你好运