django 用动态列名注释
django annotate with dynamic column name
我在 django 应用程序中有一个模型,具有以下结构:
class items(models.Model):
name = models.CharField(max_length=50)
location = models.CharField(max_length=3)
我想为每个 name/item 的每个位置的计数创建一个枢轴 table,我设法按照以下方式完成:
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
您可以在python.
中与*[1, 2, 3]
、**{'key': 'value'}
绑定动态参数
from django.db.models import Case, Count, Sum, IntegerField, Value, When
def get_annotation(key):
return {
key: Sum(
Case(
When(location=key, then=Value(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
.
即可实现一组查询
我在 django 应用程序中有一个模型,具有以下结构:
class items(models.Model):
name = models.CharField(max_length=50)
location = models.CharField(max_length=3)
我想为每个 name/item 的每个位置的计数创建一个枢轴 table,我设法按照以下方式完成:
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
您可以在python.
中与*[1, 2, 3]
、**{'key': 'value'}
绑定动态参数
from django.db.models import Case, Count, Sum, IntegerField, Value, When
def get_annotation(key):
return {
key: Sum(
Case(
When(location=key, then=Value(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
.