2017-05-09 9 views
1

現在、事前に計算JSONを返す私はこれがあります。ジャンゴRestFramework

class MySerializer(serializers.ModelSerializer): 

    class Meta: 
     model = MyModel 
     fields = (
      'id', 'f0', 'f1', 'f2') 

をそして、それはこのようなものを返します:

{ 
    "count": 6242, 
    "previous": null, 
    "total_pages": 209, 
    "results": [ 
     { 
      "id": 63915, 
      "f0": "Some stuff" 
      ..... 
     }, 
     { 
      "id": 63916, 
      "f0": "Some other stuff" 
      ..... 
     }....    

    ] 
} 

をそして、これは良いですが、私は、データをシリアライズすることは実際には非常にあることに気づきましたオンザフライで高価なので、私はそれを事前計算したいと思います。これまでのところ、私はそれを事前に計算し、私のモデルのためjsonfieldでそれを保存するために管理して、問題は私のAPIである今{「json_repersentationを」:{myold_response}}戻っている

class MySerializer(serializers.ModelSerializer): 

    class Meta: 
     model = MyModel 
     fields = ('json_representation',) 

私の質問は、それが可能です{'json_representation':{id:0、f0:label ...}}の "オーバーヘッド"なしにjson_representationフィールドに含まれるjsonを単に返すように変更し、代わりに単純に{id:0、f0:label ...}

答えて

1

あなたはシリアライザto_representationメソッドオーバーライドすることができます。

def to_representation(self, instance): 
    data = super(MySerializer, self).to_representation(instance) 
    return data['json_representation'] 
+0

ああ!まさに私が探していたもの!ありがとうございました。 –