2017-12-08 5 views
0

私は以下のシリアライザを持っています。私はキー:値表現を追加しようとしています。 stackoverflowで検索した後、Return list of objects as dictionary with keys as the objects id with django rest framerworkの答えに基づいて、私はto_representationメソッドを上書きしました。Django rest framework:Listapiviewのリターンキー:配列よりも値のペア辞書

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

私はあなたのコードを考えて私の見解である

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} 

いくつかの修正を加えると、ビューca 1つの項目につき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}) 
+0

resは配列ではありません。その1つの辞書 –

+0

@SanthoshYedidiはコードを更新しました。私はフードの下で認識しませんでした。LIstAPIViewはクエリーセットのすべてのオブジェクトに対してシリアライザを一度呼び出します –

関連する問題