Django api POS 分支总数的函数

Django api function for total of branches in POS

下面是我的 API 函数代码,我想 return 面包店的每个分店及其小计、税额和总计。我被赋予了这个任务,只执行这个功能。模型等其他部分已经完成。

def branch_report(request, params):
    try:
        orders = Order.objects.filter(is_removed=False).values_list('id')
        branch = BusinessBranch.objects.filter(is_removed=False).values_list('id')

        for each in branch:
            total = int(orders.objects.aggregate(total=sum('sub_total'))['total'])
            g_total = int(orders.objects.aggregate(g_total=sum('grand_total'))['g_total'])
            fbr_tax = int(orders.objects.aggregate(fbr_tax=sum('tax_amount'))['fbr_tax'])


        ctx['g_total'] = g_total
        ctx['fbr_tax'] = fbr_tax
        ctx['total'] = total
        
        for each in branch:
            return response_format(SUCCESS_CODE, SUCCESSFUL_RESPONSE_MESSAGE, g_total, fbr_tax, total)

    except Exception as e:
        return response_format(ERR_GENERIC, str(e))

我想得到这样的回复:

{
"code": 200,
"message": "Request was Successfull",
"data": {
    "branches": [
        {
            "is_admin": true,
            "with_fbr_sub_total": null,
            "with_fbr_tax_amount": null,
            "with_fbr_grand_total": null,
            "without_fbr_sub_total": null,
            "without_fbr_tax_amount": null,
            "without_fbr_grand_total": null,
            "sub_total": null,
            "tax_amount": null,
            "grand_total": null,
            "id": 10,
            "name": "Bedian Road",
            "till_list": 
            }
        ]
        }

这里适合您的正确答案是使用 .annotate() 我相信。 沿着这些线的东西:

from django.db.models import Sum, Q
branches = BusinessBranch.objects.filter(
    is_removed=False,
).annotate(
    total=Sum('orders__sub_total', filter=Q(orders__is_removed=False)),
    g_total=Sum('orders__grand_total', filter=Q(orders__is_removed=False)),
    fbr_tax=Sum('orders__tax_amount', filter=Q(orders__is_removed=False)),
)

您可以在我提供给 Django 文档的 link 中找到更多示例。