我遇到了一个问题,但在任何地方都找不到解决方案。
模型中的列是
category
date
amount
我需要获取每个类别的总金额并显示在每个月的模板中。像这样的东西
Category---month1---Month2
A 100 180
B 150 200
我尝试过以下查询,但似乎不起作用。
queryresult = model.objects.filter().values('category').annotate(total='amount')
它确实给出了每个类别的总数,但我如何按月安排它。基本上每个月的类别总数?
编辑: 尝试以以下格式检索查询结果:
categoryA{
month1{total}
month2{total}
}
categoryB{
month1{total}
month2{total}
}
使用 Django ORM 无法直接构建查询,您可能需要根据 Python 中的要求构建它。
from itertools import groupby
from operator import itemgetter
from django.db.models.functions import ExtractMonth
# adjust the query set as per your requirements
quesryset = model.objects.values('category', month=ExtractMonth('date')).annotate(total=Sum('amount')).order_by(
'category', 'month')
# Process query set in python to get desired output
result_dict = {}
for category, entries in groupby(quesryset, key=itemgetter('category')):
result_dict[category] = [{'month': entry['month'], 'total': entry['total']} for entry in entries]