【问题标题】:Django rest framework: Listapiview return key:value pair dictionary than an arrayDjango rest框架:Listapiview返回键:值对字典比数组
【发布时间】:2018-05-22 14:33:31
【问题描述】:

我有以下序列化程序:我正在尝试添加键:值表示。在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",
        }
    }

【问题讨论】:

    标签: django django-rest-framework


    【解决方案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})
    

    【讨论】:

    • res 不是数组。它是一本字典
    • @SanthoshYedidi 更新了代码,我不知道 LIstAPIView 会为查询集中的每个对象调用一次序列化程序
    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 2014-10-16
    相关资源
    最近更新 更多