2017-09-04 65 views
1

我試圖用django orm模型運行這個sql查詢,需要一些幫助。在django中加入一列的總和

SELECT SUM(CAPITAL) AS PRODUCT_CAPITAL, PRODUCT FROM CAPITAL_SHEET 
WHERE CLIENT_ID = 'X1234' 
GROUP BY PRODUCT 

我這樣做

CapitalSheet.objects.filter(client_id="X1234").values("product").annotate(Sum("capital")) 

這是我得到在JSON結果:

[ 
    { 
     "product": "product1" 
    }, 
    { 
     "product": "product2" 
    } 
] 

我期待這是輸出:

[ 
    { 
     "product": "product1", 
     "capital": 1234.00 
    }, 
    { 
     "product": "product2", 
     "capital": 1234.00 
    } 
] 

這裏是我的看法:

class CapitalListView(ListAPIView): 
    serializer_class = CapitalSheetSerializer 

    def get_queryset(self): 
     return CapitalSheet.objects.filter(client_id="X1234").values("product").annotate(Sum("capital")) 

這裏是我的模型:

class CapitalSheet(models.Model): 
    log_id = models.AutoField(db_column='LOG_ID', primary_key=True) 
    client_id = models.CharField(db_column='CLIENT_ID', max_length=25) 
    capital = models.DecimalField(db_column='CAPITAL', max_digits=10, decimal_places=2, blank=True, null=True) 
    payout_booked_profit = models.DecimalField(db_column='PAYOUT_BOOKED_PROFIT', max_digits=10, decimal_places=2, blank=True, null=True) 
    voucher_number = models.CharField(db_column='VOUCHER_NUMBER', max_length=45, blank=True, null=True) 
    ledger_date = models.DateField(db_column='LEDGER_DATE', blank=True, null=True) 
    amount = models.DecimalField(db_column='AMOUNT', max_digits=10, decimal_places=2, blank=True, null=True) 
    product = models.CharField(db_column='PRODUCT', max_length=45, blank=True, null=True) 
    transaction_type = models.CharField(db_column='TRANSACTION_TYPE', max_length=45, blank=True, null=True) 
    sebi_payin_flag = models.IntegerField(db_column='SEBI_PAYIN_FLAG', blank=True, null=True) 
    dividend_payout_flag = models.IntegerField(db_column='DIVIDEND_PAYOUT_FLAG', blank=True, null=True) 

我的串行:

class CapitalSheetSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = CapitalSheet 
     fields = ['capital','product'] 

我到底錯在這裏做什麼?

+0

怎麼你得到'json'?顯示代碼請 –

+0

請添加代碼'CapitalSheetSerializer' –

+0

我已更新此問題。 – Zed

回答

1

嘗試,爲註釋列添加名稱:

CapitalSheet.objects.filter(
    client_id="X1234" 
).values("product").annotate(capital=Sum("capital")) 
#       ^^^^^^^ 
+0

謝謝,現在我意識到我在做錯了什麼,我曾嘗試過這種'.annotate(total = Sum(「capital」))',現在我知道字段名稱應該與您嘗試的列名稱相同來計算總和。 – Zed