大家好,有人和我有同样的问题。问题出在Django Rest Query上,我从数据库中的字段中对值进行求和。
我收到了错误:
class invoiceList(APIView):
@method_decorator(ensure_csrf_cookie)
def get(self, request, format=None):
user_pk = request.user.id
org_id = request.user.organization.id
total = OutgoingInvoice.objects.filter(organization_id=user_pk, status_id__in=[2,3]).aggregate(total=Sum('total_invoice_amount', field="total_invoice_amount"))['total']
serializer = OutgoingInvo(total, many=True)
return Response(serializer.data)
我的模特是:
total_invoice_amount = models.DecimalField(decimal_places=5, max_digits=255, blank=True, null=True)
答案 0 :(得分:1)
问题是您使用total
调用序列化程序,这是一种不可迭代的类型,即数字。
来自文档:
aggregate()是QuerySet的终止子句,在调用时,返回名称 - 值对的字典。名称是聚合值的标识符;该值是计算的聚合。
在你的情况下:
OutgoingInvoice.objects.filter(organization_id=user_pk, status_id__in=[2,3]).aggregate(total=Sum('total_invoice_amount', field="total_invoice_amount"))
# >> {'total': 123.5} (example value)
我不知道您希望序列化程序显示什么,但如果您想要为每个用户计算总额,则可以执行以下操作:
User.objects.annotate(total=Sum("outgoing_invoice_set__total_invoice_amount")).filter(pk=user_pk, status_id__in=[2, 3])