获取错误“元组”对象没有属性“值”

时间:2020-09-14 16:57:47

标签: django-rest-framework

class budgetSerializer(serializers.ModelSerializer):
       
    budget_used        = serializers.SerializerMethodField()
    budget_remain      = serializers.SerializerMethodField()
    total_budget       = serializers.IntegerField(default=250000)


    def get_budget_used (self,obj):
            budget_used=budget.objects.filter(user=obj.user).aggregate(Sum('budget_stord__bytes'))
            data = []
            for val in budget_used.items():
                if val.value > total_budget :
                    raise serializers.ValidationError('you exceed the total budget limit')
           
            return f'budget : {(budget_used/1000)} '

    def get_total_budget(self,obj):
            total_budget = 250000
            return f'total_budget: {(total_budget/1000)} '   
    def get_remain(self,obj):
            remain = (total_budget) - (budget_used)   
            return remain

    class Meta:
        model  = budget_u
        fields = ("budget_used","total_budget","budget_remain")
MODEl 

class budget_u(CreatedModel, UUIDPKModel):
    budget_stord = models.ForeignKey('bud.Store', on_delete=models.SET_NULL, null=True, blank=True)
    user = models.ForeignKey('user.user', on_delete=models.SET_NULL, null=False, blank=False)

我需要类似的输出

{
    " budget_used": "100",
    "remain": "150G",
    "total_budget": "250"
} 

获取 AttributeError:“元组”对象没有属性“值”

1 个答案:

答案 0 :(得分:0)

您不使用std访问该值,.value返回一个2元组的迭代,因此可以在.items()循环中使用迭代拆包。但是在这里,您只需使用下标即可访问值:

for

话虽这么说,每次返回字符串都比较 odd 。序列化程序通常会返回数字数据,因为数字数据更易于处理,例如通过浏览器端的JavaScript脚本或客户端集成。