models.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)


serializers.py

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


views.py

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


如果我们在此视图中过​​滤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
    }
]
}


我想汇总结果中的所有“佣金”字段,并将总和附加到原始查询集(也许在“计数”旁边:18),如上所示,有18个佣金需要计数。

我该如何实施?需要您的帮助,谢谢!

最佳答案

尝试覆盖list()ModelViewset方法,

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

    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


此答案总结特定页面中的commision并显示它

更新

from django.db.models import Sum


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

    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


上面的答案将返回带过滤器的commission列的总和(与分页无关)
感谢@bruno提到这样的观点

关于python - 在Django的queryset中总结一个字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51554553/

10-12 21:50