这是我的序列化器:
class MySerializer(serializers.Serializer):
amount1 = serializers.SerializerMethodField(read_only=True)
amount2 = serializers.SerializerMethodField(read_only=True)
amount3 = serializers.SerializerMethodField(read_only=True)
total = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Amount
fields = "__all__"
def get_amount1(self,obj):
"""very large calculation here"""
return 5
def get_amount2(self,obj):
"""very large calculation here"""
return 10
def get_amount3(self,obj):
"""very large calculation here"""
return 15
def get_total(self,obj):
return self.get_amount1 +self.get_amount2+self.get_amount3
现在,我想在total
字段中显示所有三个金额的总和,但是由于上述方法中的大量计算,这花费了太多时间,并且它们只为获得total
而计算了两次
如何在不计算两次amount1
,amount2
,amount3
的情况下获得get_amount1
,get_amount2
,get_amount3
的总和?>
答案 0 :(得分:1)
您可以在单个序列化程序实例中使用getattr
:
def get_amount1(self,obj):
"""very large calculation here"""
if getattr(self, 'amount1', None):
return self.amount1
self.amount1 = 5
return self.amount1
def get_amount2(self,obj):
"""very large calculation here"""
if getattr(self, 'amount2', None):
return self.amount2
self.amount2 = 10
return self.amount2
def get_amount3(self,obj):
"""very large calculation here"""
if getattr(self, 'amount3', None):
return self.amount3
self.amount3 = 15
return self.amount4
def get_total(self,obj):
return self.get_amount1(obj) +self.get_amount2(obj)+self.get_amount3(obj)
或者如评论lru_cache
中提到的@ Willem-Van-Onsem所述,以获得更广泛的缓存:
@lru_cache
def get_amount1(self,obj):
"""very large calculation here"""
return 5
@lru_cache
def get_amount2(self,obj):
"""very large calculation here"""
return 10
@lru_cache
def get_amount3(self,obj):
"""very large calculation here"""
return 15