Django api функция для получения общего количества филиалов в POS
Ниже приведен мой код для функции api, я хочу вернуть каждый филиал пекарни с их суб-суммой, суммой налога и общей суммой. Мне дали задание сделать только эту функцию. Остальные части, такие как модели и т.д. уже выполнены.
'''
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.