我在 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')
这给出了每个名称在每个位置上出现的次数,这一切都可以。
我的问题是如何使位置动态化,因此如果添加了新位置,我就不会再回来更改代码!来自列表或模型数据本身
非常感谢
AB