首页 > 解决方案 > 有没有办法在 Django Rest Framework 中聚合一个字段,该字段将汇总一个字段

问题描述

目前我已经弄清楚如何在我的 serializers.py 中聚合单个列,但是我的薪水字段的总和将转到我的序列化程序中的total_salary字段,而我的模型中没有total_salary 。现在我的问题是我怎样才能在下面的 API 中做这样的事情:

"total_salary": 1422.05,
{
        "id": "8c1810d9-b799-46a9-8506-3c18ef0067f8",
        "date": "2019-04-27",
        "virtual_assistant": "Joevie",
        "time_in": "2019-04-27T22:20:13+08:00",
        "time_out": "2019-04-28T05:20:13+08:00",
        "hours": "7.00",
        "client_name": "landmaster",
        "rate": "90.00",
        "salary": "630.00",
        "status": "APPROVED-BY-THE-MANAGER",
        "notes": ""
    },

现有的是这样的。

 {
        "id": "8c1810d9-b799-46a9-8506-3c18ef0067f8",
        "total_salary": 1422.05,
        "date": "2019-04-27",
        "virtual_assistant": "Joevie",
        "time_in": "2019-04-27T22:20:13+08:00",
        "time_out": "2019-04-28T05:20:13+08:00",
        "hours": "7.00",
        "client_name": "landmaster",
        "rate": "90.00",
        "salary": "630.00",
        "status": "APPROVED-BY-THE-MANAGER",
        "notes": ""
 },

目前我做的一个解决方法是我现在在 ListView 中得到工资的总和,每次用户都会搜索一个特定的月份。计算将根据用户搜索的月份而变化。代码如下。

def get(self, request, *args, **kwargs):
        search = request.GET.get('search')
        user = request.user.staffs.full_name
        current_month = datetime.date.today().month
        current_year = datetime.date.today().year
        payroll_list = VaPayroll.objects.all()
        payroll_data = payroll_list.filter(Q(virtual_assistant=user),
                                           Q(date__month=current_month),
                                           Q(status='APPROVED-BY-THE-MANAGER'))
        total_salary = VaPayroll.objects.filter(Q(virtual_assistant=user), 
                                                Q(date__month=current_month),
                                                Q(status='APPROVED-BY-THE-MANAGER'),
                                                Q(date__year=current_year)).aggregate(Sum('salary'))
        if search:
            payroll_data = payroll_list.filter(Q(virtual_assistant=user),
                                               Q(status='APPROVED-BY-THE-MANAGER'),
                                               Q(date__icontains=search))
            total_salary = VaPayroll.objects.filter(Q(virtual_assistant=user),
                                                    Q(status='APPROVED-BY-THE-MANAGER'),
                                                    Q(date__month=search),
                                                    Q(date__year=current_year)).aggregate(Sum('salary'))
        context = {
            'total_salary': total_salary,
            'payroll_data': payroll_data
        }
        return render(request, self.template_name, context)

这是来自我的 serializers.py

class VaPayrollSerializer(serializers.ModelSerializer):
    total_salary = serializers.SerializerMethodField()

    class Meta:
        model = VaPayroll
        fields = '__all__'

    def get_total_salary(self, obj):
        user = self.context['request'].user.staffs.full_name
        totalsalary = VaPayroll.objects.filter(Q(status='APPROVED-BY-THE-MANAGER'),
                                               Q(virtual_assistant=user),
                                               Q(date__month=datetime.date.today().month),
                                               Q(date__year=datetime.date.today().year)).aggregate(total_salary=Sum('salary'))
        return totalsalary['total_salary']

这是来自我的模型视图集的get_queryset

def get_queryset(self):
        current_month = datetime.date.today().month
        current_year = datetime.date.today().year
        queryset = VaPayroll.objects.filter(Q(virtual_assistant=self.request.user.staffs.full_name), 
                                            Q(date__month=current_month), 
                                            Q(date__year=current_year))
        return queryset

在我计划的用例中,我希望在我的 API 中有一个包含所有工资总和的列,这样我就可以在前端单独调用该字段,而无需刷新页面来重新计算总工资。或者这是正确的方法吗?或者我应该坚持使用视图来重新计算总工资。

标签: djangodjango-rest-frameworkdjango-rest-viewsets

解决方案


您无法以您想要的方式获取 json,因为它不是有效的 json 格式。我的建议是尝试这样的事情:

"salary": {
           "total": 1422.05,
           "detail": {
                      "id": "8c1810d9-b799-46a9-8506-3c18ef0067f8",
                      "date": "2019-04-27",
                      "virtual_assistant": "Joevie",
                      "time_in": "2019-04-27T22:20:13+08:00",
                      "time_out": "2019-04-28T05:20:13+08:00",
                      "hours": "7.00",
                      "client_name": "landmaster",
                      "rate": "90.00",
                      "salary": "630.00",
                      "status": "APPROVED-BY-THE-MANAGER",
                      "notes": ""
             }
      }

为此,您必须使用to_representation()以下方法指示您的序列化程序:

class VaPayrollSerializer(serializers.ModelSerializer):
    class Meta:
        model = VaPayroll
        fields = '__all__'

    def to_representation(self, instance):
        original_representation = super().to_representation(instance)

        representation = {
            'total': self.get_total_salary(instance),
            'detail': original_representation,
        }

        return representation

    def get_total_salary(self, obj):
        user = self.context['request'].user.staffs.full_name
        totalsalary = VaPayroll.objects.filter(Q(status='APPROVED-BY-THE-MANAGER'),
            Q(virtual_assistant=user),
            Q(date__month=datetime.date.today().month),
        Q(date__year=datetime.date.today().year)).aggregate(total_salary=Sum('salary'))

        return totalsalary['total_salary']

推荐阅读