将对象属性总和添加到Django Rest Framework响应中

时间:2018-08-23 03:10:32

标签: django django-models django-rest-framework

我正在尝试将多个对象的总和添加到DRF响应中。例如,现在响应仅用于列出对象:

[
    {
        "id": "47d0deaa5c8c",
        "amount": "25.00"
    },
    {
        "id": "29787731",
        "amount": "25.00"
    }
]

但是我想要的是能够将这些对象的数量属性加在一起,然后将其包括在响应中,这样看起来像这样:

{  
   "sum":"50.00",
   "objects":[  
      {  
         "id":"47d0deaa5c8c",
         "amount":"25.00"
      },
      {  
         "id":"29787731",
         "amount":"25.00"
      }
   ]
}

这是我当前的APIView:

class TransactionsList(GenericAPIView):
"""
Retrieve list of transactions
"""

authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)

def get(self, request):
    """List Transactions"""
    transaction = Transaction.objects.all()
    serializer = TransactionSerializer(transaction, many=True)
    return Response(serializer.data)

和序列化器:

class TransactionSerializer(serializers.ModelSerializer):

class Meta:
    model = Transaction
    fields = ('id', 'amount')

如何有效地将求和字段添加到响应中?

2 个答案:

答案 0 :(得分:2)

更改

return Response(serializer.data)

from django.db.models import Sum
all_sum = transaction.aggregate(Sum('amount'))['amount__sum']
return Response({'sum': all_sum if all_sum else 0 , 'objects': serializer.data})

答案 1 :(得分:1)

由于 amount 字段显示为 string 类型。因此,我们必须先将其转换为 int

class TransactionsList(GenericAPIView):
    """
    Retrieve list of transactions
    """
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        """List Transactions"""
        transaction = Transaction.objects.all()
        serializer = TransactionSerializer(transaction, many=True)
        return_data = {"sum": str(sum([lambda items: int(items['amount'])])), "objects": serializer.data}
        return Response(return_data)


如果金额字段为int类型,则您不想添加类型强制转换。如果是这样,请使用

return_data = {"sum": sum([lambda items: items['amount']]), "objects": serializer.data}