代码之家  ›  专栏  ›  技术社区  ›  Somil

获取Django REST中的amount字段结果之和

  •  1
  • Somil  · 技术社区  · 6 年前

    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 但由于上述方法计算量大,计算时间长,而且只需计算两次即可得到 全部的

    我怎样才能得到 amount1 , amount2 , amount3 get_amount1 , get_amount2 , get_amount3

    1 回复  |  直到 6 年前
        1
  •  2
  •   neverwalkaloner    6 年前

    你可以用 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)
    

    或者正如@Willem Van Onsem在评论中提到的那样 lru_cache 对于更广泛的缓存:

    @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