bluepnume
bluepnume

Reputation: 17158

Django query grouping result

OK, so I have the following model:

Transaction
  currency_code: CharField
  date_time: DateTimeField
  price:     IntegerField

I'd like to make a query which returns a dictionary of distinct days, with totals for all transactions under each currency_code. So something like:

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

So far I've got this query, but I'm kind of stuck:

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

This gets me a result which looks like the following:

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

Any advice on how I can get my query to group by date? Thanks in advance!

Upvotes: 1

Views: 157

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174758

Here's a non-ORM approach to get things done:

>>> 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}})

Here is the groupby version:

>>> 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}]

Upvotes: 1

Related Questions