Django休息框架:Listapiview返回键:值对字典比数组

时间:2017-12-08 10:48:44

标签: django django-rest-framework

我有以下序列化程序:我正在尝试添加键:值表示。在stackoverflow上搜索后,基于Return list of objects as dictionary with keys as the objects id with django rest framerwork的答案,我已经覆盖了to_representation方法。

class IngredientListSerializer(ModelSerializer):
    class Meta:
        model = Ingredient
        fields = '__all__'

    def to_representation(self, data):
        res = super(IngredientListSerializer, self).to_representation(data)
        return {res['id']: res}

我的观点是:

class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer

输出如下:

"results": [
        {
            "172": {
                "id": 172,
                "name": "rice sevai",
            }
        },
        {
            "218": {
                "id": 218,
                "name": "rocket leaves",
            }
        }
    ]

我正在寻找的输出是:

"results": {
        "172": {
            "id": 172,
            "name": "rice sevai",
        },
        "218": {
            "id": 218,
            "name": "rocket leaves",
        }
    }

1 个答案:

答案 0 :(得分:1)

我认为您的代码经过一些修改应该可以工作,因为视图会对每个项目调用序列化程序.to_representation()一次,您可以处理序列化程序的结果。虽然为您的案例使用通用视图可能会更好

class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        data = {obj['id']: obj for obj in serializer.data}
        return Response({'results': data})