我正在尝试使用django orm模型运行此sql查询。
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 :(得分:1)
尝试一下,为注释列添加名称:
CapitalSheet.objects.filter(
client_id="X1234"
).values("product").annotate(capital=Sum("capital"))
# ^^^^^^^