Django按月注释组

时间:2016-05-23 19:28:15

标签: django aggregate

如何按月汇总价格?

我试试。

import itertools
qs = Contract.objects.values('created', 'proposal__price')
grouped = itertools.groupby(qs, lambda d: d.get('created').strftime('%Y-%m'))
data = [{'month': month, 'quant': sum(list(this_day))} for month, this_day in grouped]
print(data)

但结果并非预期。

我需要这个类似的结果

[{'month': '2016-04', 'quant': 8650}, {'month': '2016-05', 'quant': 9050}]

3 个答案:

答案 0 :(得分:1)

this_day sum(list(this_day))内的dict>>> import itertools >>> from django.contrib.auth.models import User >>> li = User.objects.all().values('date_joined', 'username') >>> gr = itertools.groupby(li, lambda d: d.get('date_joined').strftime('%Y-%m')) >>> dt = [{'m': m, 'q': sum([len(x['username']) for x in q])} for m, q in gr] >>> dt [{'m': '2005-06', 'q': 11}, {'m': '2006-10', 'q': 22}, {'m': '2005-06', 'q': 179}, {'m': '2006-08', 'q': 10}, {'m': '2006-09', 'q': 30}, {'m': '2005-06', 'q': 74}, ... ] ,因此您需要构建一个包含列表解析的列表。实施例

data = [{'month': month, 'quant': sum([x['proposal__price'] for x in this_day])} 
        for month, this_day in grouped]

或者,对于您的代码,可能是这样的

echo -n -e \\xff\\x90\\x12\\x34 > sourceFile

答案 1 :(得分:0)

首先提取月份和所有值

from django.db import connection
select = {'month': connection.ops.date_trunc_sql('month', 'created')}
qs = Contract.objects.extra(select=select).values('month').annotate(my_total=Sum('proposal__price'))

现在我们可以使用一个函数按dict键分组:

from itertools import groupby
from operator import attrgetter
get_y = attrgetter('month')
from collections import defaultdict, Counter
def solve(dataset, group_by_key, sum_value_keys):
    dic = defaultdict(Counter)
    for item in dataset:
        key = item[group_by_key]
        vals = {k:item[k] for k in sum_value_keys}
        dic[key].update(vals)
    return dic

将其应用于您的查询集的新注释my_total,按month分组:

solved = solve(qs, 'month', ['my_total'])

您按月分组总和(月份为日期时间对象,您可以更改操作以满足您的需求):

for i in solved: print(i, ":", solved[i]['my_total'])
>>> datetime.datetime(2015, 9, 1, 0, 0, tzinfo=<UTC>) : 67614.23
>>> datetime.datetime(2015, 1, 1, 0, 0, tzinfo=<UTC>) : 54792.39

现在您可以提取这些值:)

答案 2 :(得分:0)

我的代码改编自@ C14L。

import itertools
# from .models import Contract
c = Contract.objects.all().values('created', 'proposal__price')
gr = itertools.groupby(c, lambda d: d.get('created').strftime('%Y-%m'))
dt = [{'month': month, 'quant': sum([x['proposal__price'] for x in quant])} for month, quant in gr]
dt

感谢。