Django的注释与动态列名

问题描述 投票:0回答:1

我有Django应用程序的模型,结构如下:

class items(models.Model):
    name = models.CharField(max_length=50)
    location = models.CharField(max_length=3)

我想创建一个数据透视表每每个名称/项目,这是我能够做到按以下每个位置的计数:

queryset_res = items.objects.values('name')\
                            .annotate(NYC=Sum(Case(When(location='NYC', then=1),default=Value('0'),output_field=IntegerField())))\
                            .annotate(LND=Sum(Case(When(location='LND', then=1),default=Value('0'),output_field=IntegerField())))\
                            .annotate(ASM=Sum(Case(When(location='ASM', then=1),default=Value('0'),output_field=IntegerField())))\
                            .annotate(Total=Count('location'))\
                            .values('name', 'NYC', 'LSA','Total')\
                            .order_by('-Total')

这使我每个名字出现了多少次打击是一切ok每个位置。

我的问题是如何使位置动态的,所以如果在那里加入我不回来了,并再次更改代码的新位置!无论是从列表或从模型数据本身

非常感谢AB

django dynamic pivot annotate
1个回答
2
投票

你可以绑定*[1, 2, 3]动态参数,**{'key': 'value'}的蟒蛇。

def get_annotation(key='NYC'):
    return {
        key: Sum(Case(When(localtion=key), then=1), default=Value('0'), output_field=IntegerField()),
    }

queryset_res = items.objects.values('name')
location_list = ['NYC', 'LSA', 'ASM', ...etc]
for key in location_list:
    queryset_res = queryset_res.annotate(**get_annotation(key))

queryset_res = queryset_res.annotate(Total=Count('location')) \
    .values('name', 'Total', *location_list) \
    .order_by('-Total')

现在,你可以简单地通过改变location_list实现的一组查询。

© www.soinside.com 2019 - 2024. All rights reserved.