Django DRF如何使用to_representation和to_internal_value?

时间:2016-02-06 03:05:17

标签: django django-rest-framework

documentation非常简短,我无法通过阅读source code来弄清楚如何使用它。

以下是我想在伪代码中完成的事情:

def transform_result(self, data):
    ret = {}
    for entry in data:
        type = entry['type']
        if type in ret:
            ret[type].add({entry['id'], entry['tag']})
        else:
            new_type = ret.add(type)
            new_type.add({entry['id'], entry['tag']})
    return ret

哪个应该这样:

[
    {
        "id": 1,
        "type": "Color",
        "tag": "Blue"
    },
    {
        "id": 2,
        "type": "Color",
        "tag": "Red"
    },
    {
        "id": 3,
        "type": "Shape",
        "tag": "Square"
    },
]

并将其转换为:

[
    {
        "type": "Color",
        "tags": [
            {
                "id": 1,
                "tag": "Blue"
            },
            {
                "id": 2,
                "tag": "Red"
            }
        ]
    },
    {
        "type": "Shape",
        "tags": [
            {
                "id": 3,
                "tag": "Square"
            }
        ]
    }
]

是否应使用to_representationto_internal_value完成此操作?如果是这样,怎么办呢?

0 个答案:

没有答案