gpt4 book ai didi

python - 对 Django 中的查询集中的一个字段求​​和

转载 作者:行者123 更新时间:2023-12-01 01:44:24 25 4
gpt4 key购买 nike

模型.py

class QaCommission(models.Model):
user = models.ForeignKey(PlUser, on_delete=models.CASCADE, blank=True, null=True, related_name='user_commission')
ref = models.ForeignKey(PlUser, on_delete=models.CASCADE, blank=True, null=True, related_name='ref_commission')
price = models.FloatField(blank=True, null=True)
pct = models.FloatField(blank=True, null=True)
commission = models.FloatField(blank=True, null=True)
status = models.IntegerField(blank=True, null=True, default=0)

序列化器.py

class QaCommissionSerializer(serializers.ModelSerializer):
class Meta:
model = QaCommission
fields = '__all__'

View .py

class QaCommissionList(viewsets.ModelViewSet):
queryset = QaCommission.objects.all()
serializer_class = QaCommissionSerializer

如果我们在此 View 中过​​滤 ref=60,结果显示如下:

{
"count": 18,
"next": "http://127.0.0.1:8008/api/qacommission/?ref=60&page=2",
"previous": null,
"results": [
{
"id": 1,
"price": 20.0,
"pct": 0.1,
"commission": 2.0,
"status": 1,
"user": 7,
"ref": 60
},
{
"id": 2,
"price": 10.0,
"pct": 0.1,
"commission": 1.0,
"status": 1,
"user": 7,
"ref": 60
},
......
......
......
{
"id": 10,
"price": 15.0,
"pct": 0.1,
"commission": 1.5,
"status": 1,
"user": 7,
"ref": 60
}
]
}

我想对结果中所有的“commission”字段求和,并将总和附加到原始查询集(可能在“count”:18旁边),如上所示,有18个佣金需要计算。

我该如何实现这个?需要您的帮助,谢谢!

最佳答案

尝试将 ModelViewsetlist() 方法重写为,

class QaCommissionList(viewsets.ModelViewSet):
queryset = QaCommission.objects.all()
serializer_class = QaCommissionSerializer

<b>def list(self, request, *args, **kwargs):
response = super().list(request, *args, **kwargs)
response.data['sum'] = sum([data.get('commission', 0) for data in response.data['results']])
return response</b>

此答案总结了特定页面佣金并显示出来

更新

<b>from django.db.models import Sum</b>


class QaCommissionList(viewsets.ModelViewSet):
queryset = QaCommission.objects.all()
serializer_class = QaCommissionSerializer

<b>def list(self, request, *args, **kwargs):
response = super().list(request, *args, **kwargs)
if 'ref' in request.GET and request.GET['ref']:
response.data['sum'] = QaCommission.objects.filter(ref=int(request.GET['ref'])
).aggregate(sum=Sum('commission'))['sum']
return response</b>

上述答案将返回过滤器的commission列的总和(与分页无关)

谢谢@bruno提到这样一个有效的观点

关于python - 对 Django 中的查询集中的一个字段求​​和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51554553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com