Djangorestframework将关系序列化为字典,而不是数组

2024-06-25 23:57:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将外键序列化为字典而不是数组。 现在json看起来如下所示:

{
"slug": "en",
"children": [{
        "slug": "pants",
        "children": [{
                "slug": "products/:level1",
                "children": [{
                    "slug": ":level2/:level3",
                    "children": []
                }]
            },
            {
                "slug": ":productSlug",
                "children": []
            }
        ]
    },
    {
        "slug": "pullovers",
        "children": []
    }
   ]
}

但我想用鼻涕虫做钥匙:

{
"en": {
    "children": {
        "pants": {
            "children": {
                "products/:level1": {
                    "children": {
                        ":level2/:level3": {
                            "children": {}
                        }
                    }
                }
            },
            ":productSlug": {
                "children": {}
            }
        ]
    }
 }
}

是否可以直接在序列化程序中进行转换,还是必须在附加步骤中进行转换?你知道吗


Tags: json字典序列化数组外键enpantsproducts
2条回答

@Michael Rigonis答案(https://stackoverflow.com/a/45238191/270265)是成功的关键。我不得不对它稍加调整,所以我也可以将它用于顶级

class DictSerializer(serializers.ListSerializer):
    key = None

    def __init__(self, *args, **kwargs):
        self.key = kwargs.pop('key', self.key)
        super().__init__(*args, **kwargs)

    def to_representation(self, data):    
        r = super().to_representation(data)
        return {item[self.key]: item for item in r}

    @property
    def data(self):
        # This is a bit nasty, because the only "Many-Serializer" is a ListSerializer we inherit of it,
        # but when converting it to json we call the BaseSerializer directly, because we want a Dictionary rather then a list
        ret = super(serializers.ListSerializer, self).data
        return ReturnDict(ret, serializer=self)

可以通过重写list serializers并为每个需要它的序列化程序设置list_serializer_class,正如我在answer中所建议的那样。你知道吗

当然,您需要稍微调整一下:

class <YourClass>ListSerializer(serializers.ListSerializer):
    def to_representation(self, data):
        r = super().to_representation(data)

        return { item['<key_field>']: item for item in r }

相关问题 更多 >