Sharing heavy calculations result when using DRF serializer with many=True <p>There is a simple DRF serializer which:</p> <pre><code>class MySeriliazer(serializers.Serializer): some_field = serializers.SerializerMethodField(read_only=True) def get_some_field(self, obj): some_list = utils.do_some_heavy_calculations() return some_list[obj.some_field] </code></pre> <p>As you see I have a <code>some_field</code> field which value is calculated via some function.</p> <p>When I get a single object it's a big of a problem, but when I use this serializer with <code>many=True</code> thus receiving multiple objects <code>do_some_heave_calculations</code> get called for each, which is very expensive.</p> <p>Moreover sometimes there are few fields which use the same heavy function. like:</p> <pre><code>class MySeriliazer(serializers.Serializer): some_field1 = serializers.SerializerMethodField(read_only=True) some_field2 = serializers.SerializerMethodField(read_only=True) def get_some_field1(self, obj): some_list = utils.do_some_heavy_calculations() return some_list[obj.some_field1] def get_some_field2(self, obj): some_list = utils.do_some_heavy_calculations() return some_list[obj.some_field2] </code></pre> <p>Function is called twice for each object. Not good. What are the options to solve this? Sure enough I can grab these results from some cache which is updated every second. But I think it's possible to extract these calculations somehow and share them during the serialization process.</p> <p>If needed - I use DRF generic views.</p>