transpose values_list result from ORM

119 views
Skip to first unread message

Florian Auer

unread,
Oct 2, 2014, 10:50:32 AM10/2/14
to django...@googlegroups.com
Hi

I have a ORM query that results something like this:
+---------+-----+-------+
|  date   | key | value |

+---------+-----+-------+
| 201312  |  A  | 123   |
| 201312  |  B  | 223   |
| 201312  |  C  | 133   |
| 201311  |  A  | 173   |
| 201311  |  B  | 463   |
| 201311  |  C  | 463   |
+---------+-----+-------+

As far as i know, django cannot transpose a query so i need do get this into the following format in another way:
+---------+-----+-----+-----+
|  date   |  A  |  B  |  C  |

+---------+-----+-----+-----+
| 201312  | 123 | 223 | 133 |
| 201311  | 173 | 463 | 463 |
+---------+-----+-----+-----+

I tried something like a loop and the setdefault(), but my knowledge in python seems to be too poor.
kzlist = XYZ.objects.filter(...).values_list('date', 'key', 'value')
data = {}
for kz in klist:
    data.setdefault(kz['date'], {}).update({'%s' % kz['key'] : kz['value']})


Has anyone an advice to solve this little problem?

Collin Anderson

unread,
Oct 2, 2014, 2:03:39 PM10/2/14
to django...@googlegroups.com
Assuming "klist" is a typo, your setdefault code _should_ give you something close to what you want, though not exactly in a table. What happens when you try? 

I simplified your code slightly:
data = {}
for kz in kzlist:  # assuming klist was a typo
    data
.setdefault(kz['date'], {})[kz['key']] = kz['value']  # slightly simpler

How are you displaying the information?

Florian Auer

unread,
Oct 5, 2014, 10:07:02 AM10/5/14
to django...@googlegroups.com
Hi

the original variant was claiming a type mismatch:
Traceback (most recent call last):
 
File "<console>", line 2, in <module>
TypeError: tuple indices must be integers, not str

The same with your code example.
Maybe the reason is that date is not an integer as it looks like, but a string representation of it?

Florian Auer

unread,
Oct 5, 2014, 10:13:06 AM10/5/14
to django...@googlegroups.com
Ha, I think i got it....

the result from my databes is a values_list with tupels that cannot be acced via name.
I have to use the indizes:
for kz in kzlist:
    data
.setdefault(kz[1], {})[kz[0]] = kz[2]

Collin Anderson

unread,
Oct 5, 2014, 1:07:19 PM10/5/14
to django...@googlegroups.com
Ahh, yup. values_list(). I was thinking values()
Reply all
Reply to author
Forward
0 new messages