gpt4 book ai didi

django - 实现 prefetch_related() 方法后如何附加键和值

转载 作者:行者123 更新时间:2023-12-04 21:04:35 24 4
gpt4 key购买 nike

我已经用 GET 实现了一个基于类的 View 获取工资单详情的方法 id .我如何附加 net_allowance在工资单中 object所以JSON看起来像这样:

{
"employee__user__id": 2,
"payslip_no": "GGT5698",
"employee__user__first_name": "Nick",
"basic_salary__salary_value": 80000.0,
"net_allowances": 5400.0,
"total_deductions": 2500.0,
"payment_mode__name": "Bank",
"month_ending": "2018-03-16",
"employee__user__last_name": "Cannon"
}



class PayrollView(APIView):

def get(self, request, pk, format=None):
try:

payslip = Payslip.objects.filter(id=pk).prefetch_related('user', 'employee').values(
'payment_mode__name', 'payslip_no', 'allowances__amount', 'deductions__amount', 'month_ending', 'basic_salary__salary_value', 'employee__user__last_name', 'employee__user__first_name', 'employee__user__id'
)

net_allowance = payslip.aggregate(
net_allowance=Sum('allowances__amount'))
except Exception as e:
# print(e)
return Response(data=e, status=status.HTTP_400_BAD_REQUEST)
return Response(data=payslip, status=status.HTTP_200_OK)

最佳答案

尝试这个

payslip = Payslip.objects.filter(id=pk).prefetch_related('user', 'employee')
result = payslip.aggregate(
net_allowance=Sum('allowances__amount')).values(
'payment_mode__name', 'payslip_no', 'allowances__amount','deductions__amount', 'month_ending', 'basic_salary__salary_value',
'employee__user__last_name', 'employee__user__first_name',
'employee__user__id','net_allowance'
)

关于django - 实现 prefetch_related() 方法后如何附加键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49668508/

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