Django-数据透视

时间:2018-09-06 12:07:34

标签: python django django-views

我正在准备一份报告,其中需要的输出类似于数据透视表。我能够获得所需的输出编号,但无法获得所需的格式。

下面是我为获取数据而编写的查询。

net2 = AccountNetworkMapping.objects.filter(accountId=24).values_list('accountId__accountName','serviceFunctionName', 'networkCode',
                                                                     'cji3report__period').annotate(Sum('cji3report__valInRepCurrency'))

现在我正在使用类似这样的查询集

('Acc1', '1st Level Ops', 10048666, 1, Decimal('1996'))
('Acc1', '1st Level Ops', 10048666, 2, Decimal('1868'))
('Acc1', '1st Level Ops', 10048666, 3, Decimal('872'))
('Acc1', '2nd Level Ops', 10048667, 4, Decimal('119.4'))
('Acc1', '2nd Level Ops', 10048667, 5, Decimal('128.2'))
('Acc1', '2nd Level Ops', 10048667, 6, Decimal('127'))
('Acc1', '2nd Level Ops', 10048667, 7, Decimal('135'))
('Acc1', 'Dispatch', 10069920, None, None)
('Acc1', 'Incident Mgmt.', 10048674, 1,Decimal('6067.71
('Acc1', 'Incident Mgmt', 10048674, 2, Decimal('5276.65
('Acc1', 'Incident Mgmt', 10048674, 3, Decimal('6077.88
('Acc1', 'Incident Mgmt', 10048674, 4, Decimal('4617.83
('Acc1', 'Incident Mgmt', 10048674, 5, Decimal('5125.52
('Acc1', 'Incident Mgmt', 10048674, 6, Decimal('4630.80
('Acc1', 'Incident Mgmt', 10048674, 7, Decimal('5502.61
('Acc1', 'Operations mgmt', 10048673, 1, Decimal('1914.18'))
('Acc1', 'Operations mgmt', 10048673, 2, Decimal('9371.42'))
('Acc1', 'Operations mgmt', 10048673, 3, Decimal('6550.40'))
('Acc1', 'Operations mgmt', 10048673, 4, Decimal('5687.95'))
('Acc1', 'Operations mgmt', 10048673, 5, Decimal('5885.44'))
('Acc1', 'Operations mgmt', 10048673, 6, Decimal('448.20'))
('Acc1', 'Operations mgmt', 10048673, 7, Decimal('3393.38'))
('Acc1', 'Optimization', 10048671, 1, Decimal('17664.03'))
('Acc1', 'Optimization', 10048671, 2, Decimal('23518.47'))
('Acc1', 'Optimization', 10048671, 3, Decimal('23676.25'))
('Acc1', 'Optimization', 10048671, 4, Decimal('20782.41'))
('Acc1', 'Optimization', 10048671, 5, Decimal('34348.31'))
('Acc1', 'Optimization', 10048671, 6, Decimal('12187.35'))
('Acc1', 'Optimization', 10048671, 7, Decimal('19059.12'))
('Acc1', 'Service', 10048670, 3, Decimal('12.12'))
('Acc1', 'Service ', 10048670, 4, Decimal('12.12'))

现在我面临的问题是我想以以下格式显示以上内容

Service Function   Network  Jan  Feb  March  April  May   June  July  
1st LA Ops        10048666  1996 1868  872   0        0     0     0
2nd LA Ops        10048666    0    0    0   119.4  128.2  127   135

请指导我如何在Django中准备这张桌子

1 个答案:

答案 0 :(得分:0)

这个django库可以执行您想要的操作:https://github.com/martsberger/django-pivot。在pip install django-pivot之后,类似:

from django_pivot.pivot import pivot

result_you_want = pivot(AccountNetworkMapping.objects.filter(accountId=24),
                        ['serviceFunctionName', 'networkCode'],
                        'cji3report__period',
                        'cji3report__valInRepCurrency')

您可以指定所需的聚合为Sum,但这是默认设置。