如何在Django REST API中计算租金模型字段总和并返回总金额
如何在Django REST Framework中计算并返回字段求和的total_amount字段
要实现将rent_amount、bijli_bill、other_amount求和得到total_amount并返回目标格式的JSON,只需修改Serializer即可完成,无需改动现有Model和View代码。
修改Serializer代码
在Serializer中添加动态计算字段total_amount,通过SerializerMethodField实现求和逻辑:
from rest_framework import serializers from .models import rent class rentSerializer(serializers.ModelSerializer): rent_date = serializers.DateField(format="%d-%m-%Y", read_only=True) # 定义动态计算的输出字段 total_amount = serializers.SerializerMethodField() class Meta: model = rent # 明确列出需要返回的字段,避免返回不必要的user字段 fields = ('id', 'rent_date', 'rentmonth', 'rent_amount', 'bijli_bill', 'other_amount', 'other_commnet', 'total_amount') # 实现求和逻辑 def get_total_amount(self, obj): # 处理other_amount可能为None的情况,默认用0.0参与计算 other_amount = obj.other_amount or 0.0 return obj.rent_amount + obj.bijli_bill + other_amount
代码说明
SerializerMethodField用于定义需要动态计算的输出字段,仅作用于序列化输出(不会处理输入数据)get_total_amount方法接收当前rent实例作为参数,计算三个金额字段的总和- 由于
other_amount在模型中设置了blank=True,数据库中可能存储为None,因此用obj.other_amount or 0.0确保求和时不会抛出类型错误
验证结果
修改完成后,请求API返回的JSON数据将符合你需要的格式:
{ "id": 1, "rent_date": "23-08-2022", "rentmonth": "June", "rent_amount": 500.0, "bijli_bill": 200.0, "other_amount": 100.0, "other_commnet": "test", "total_amount": 800.0 }
内容的提问来源于stack exchange,提问作者Punit kumar
相关产品推荐
相关产品推荐

