我不能将两个字段相乘。错误:以10为基数的int()的文字无效:

时间:2019-05-25 07:47:53

标签: django django-rest-framework

我试图乘以价格和数量。但是出了点问题。 “数量”和“价格”都是IntegerField()

class BillListSum(generics.GenericAPIView):

    def get(self, request):
        bill = Bill.objects.all()
        serializer = BillSerializer(bill)
        all_sum = Bill.objects.all().aggregate(Sum(int('cart__drink__price')*'cart__quantity' ))['cart__drink__price__sum']
        return Response({'sum': all_sum if all_sum else 0 , 'objects': serializer.data})

错误:int()以10为底的无效文字:'cart__drink__price' 请帮我!非常感谢。

2 个答案:

答案 0 :(得分:1)

我认为您可以尝试这样:

from django.db.models import F, IntegerField

class BillListSum(generics.GenericAPIView):
    def get(self, request):
        ...
        all_sum = Bill.objects.all().aggregate(sum_price = Sum(F('cart__drink__price')*F('cart__quantity'), output_field=IntegerField()))['sum_price']

更新分组依据的答案

from django.db.models import F, IntegerField, ExpressionWrapper

class BillListSum(generics.GenericAPIView):
    def get(self, request):
        bill = Bill.objects.all().annotate(total_price = ExpressionWrapper(F('cart__drink__price')*F('cart__quantity'), output_field=IntegerField())).order_by('total_price')
        serializer = BillSerializer(bill)
        all_sum = bill.aggregate(sum_price=Sum(F('total_price'))).get('sum_price')
        # rest of the code

答案 1 :(得分:0)

这正是您所需要的。

from django.db import connection
from django.db.models import Sum, F

class BillListSum(generics.GenericAPIView):

    def get(self, request):
        bill = Bill.objects.all()
        serializer = BillSerializer(bill)
        all_sum = Bill.objects.all().aggregate(val=Sum(F('cart__drink__price')*F('cart__quantity')))['val']
        print(all_sum) # returns int

        print(connection.queries) # This will return queries performed in your views. make monitoring using this.

        return Response({'sum': all_sum if all_sum else 0 , 'objects': serializer.data})

如果要使用SQL GROUP BY,则应使用annotate() Manager/QuerySet方法。还请检查docs有关聚合的信息。一切都很详细。