gpt4 book ai didi

python - Django查询分组结果

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:51 26 4
gpt4 key购买 nike

好的,所以我有以下模型:

Transaction
currency_code: CharField
date_time: DateTimeField
price: IntegerField

我想进行一个查询,返回不同日期的字典,其中包含每个货币代码下所有交易的总计。所以类似:

{
'2012/05/01': {
'USD': 5000,
'EUR': 3500,
}
'2012/05/02': {
'USD' ...

到目前为止,我已经收到了这个查询,但我有点卡住了:

Transaction.objects.extra({'date' : 'date(date_time)'}).values('date', 'currency_code').annotate(Sum('price'))

这得到了如下所示的结果:

[
{'date': datetime.date(2012, 5, 1), 'price__sum': 5000, 'currency_code': 'USD'}
{'date': datetime.date(2012, 5, 1), 'price__sum': 3500, 'currency_code': 'EUR'}
...
]

关于如何让我的查询按日期分组有什么建议吗?提前致谢!

最佳答案

这是完成任务的非 ORM 方法:

>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> l = [{'a': 1, 'price': 50, 'currency': 'USD'},{'a': 1, 'price': 55, 'currency': 'USD'}, {'a': 1, 'price': 0, 'currency': 'USD'},{'a':1, 'price': 20, 'currency': 'EUR'}]
>>> for i in l:
... if i['currency'] not in d[i['a']].keys():
... d[i['a']][i['currency']] = i['price']
... else:
... d[i['a']][i['currency']] += i['price']
...
>>> d
defaultdict(<type 'dict'>, {1: {'USD': 105, 'EUR': 20}})

这是 groupby 版本:

>>> l2 = []
>>> for i,g in groupby(l, lambda x: x['currency']):
... price = 0.0
... for p in g:
... price += p['price']
... l2.append({'a': p['a'], 'total' : price, 'currency': i})
...
>>> l2
[{'a': 1, 'currency': 'USD', 'total': 105.0}, {'a': 1, 'currency': 'EUR', 'total': 20.0}, {'a': 2, 'currency': 'KWD', 'total': 2.0}, {'a': 2, 'currency': 'GBP', 'total': 21.0}]

关于python - Django查询分组结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10748459/

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