2015-05-12 84 views
0

嗨,大家好,任何人都有與我一樣的問題。問題出在Django Rest Query上,其中我從數據庫中的字段求和值。Django Rest Framewrok與總和查詢問題

我得到錯誤:

  1. Django的版本:1.7.7
  2. 異常類型:類型錯誤
  3. 異常值: '小數' 對象不是可迭代

意見

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

請發佈您的stacktrace以獲取有關此錯誤的更多詳細信息。 – Jingo

回答

1

的問題是,你正在呼籲與total串行這是一種非迭代的類型,也就是一個數字。

從文檔:

aggregate() is a terminal clause for a QuerySet that, when invoked, returns a dictionary of name-value pairs. The name is an identifier for the aggregate value; the value is the computed aggregate.

你的情況:

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]) 
+0

Thax for answer,@qwattash – marin