Reputation: 11295
Currently I have this:
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = (
'id', 'f0', 'f1', 'f2')
And it returns something like this:
{
"count": 6242,
"previous": null,
"total_pages": 209,
"results": [
{
"id": 63915,
"f0": "Some stuff"
.....
},
{
"id": 63916,
"f0": "Some other stuff"
.....
}....
]
}
And this is good, but I noticed that serializing the data is actually quite expensive to do on the fly, so I would like to precompute it. So far I've managed to precompute it and store it in a jsonfield for my model, the problem is my API is now returning {'json_repersentation':{myold_response}}
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('json_representation',)
My question is, is it possible to change it so that it simply returns the json contained within json_representation field without the "overhead" of {'json_representation':{id:0, f0:label...}} and instead just simply {id:0, f0:label...}
Upvotes: 1
Views: 58
Reputation: 3805
You can override the serializer to_representation
method:
def to_representation(self, instance):
data = super(MySerializer, self).to_representation(instance)
return data['json_representation']
Upvotes: 1